Некорректное отображение переменной - Java
Формулировка задачи:
Имеется переменная "q", по нажатию на кнопку ее значение должно увеличиваться на 1 (так и происходит), но также это все должно выводиться на экран с помощью метода paintComponent. Когда я нажимаю на кнопку, то новое значение переменной просто отображается поверх старого и так происходит и далее.
int q;
public myPanel()
{
setLayout(null);
setFocusable(true);
Timer timer = new Timer(1,new ActionListener(){
public void actionPerformed(ActionEvent e){
repaint();
}
});
timer.start();
JButton b = new JButton();
b.setText("+");
b.setBounds(159, 45, 41, 25);
b.setFocusable(false);
b.setBackground(Color.WHITE);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
q+=1;
}
});
add(b);
JButton b1 = new JButton();
b1.setText("-");
b1.setBounds(159, 75, 41, 25);
b1.setFocusable(false);
b1.setBackground(Color.WHITE);
add(b1);
}
public void paintComponent(Graphics gr)
{
gr.drawString(String.valueOf(q), 140, 80);
}Решение задачи: «Некорректное отображение переменной»
textual
Листинг программы
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestMyPanel extends JFrame {
private static final long serialVersionUID = 1L;
TestMyPanel() {
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new MyPanel());
setVisible(true);
}
public static void main(String[] args) {
new TestMyPanel();
}
private class MyPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton plusButton, minusButton;
int q = 0;
MyPanel() {
setLayout(null);
setFocusable(true);
plusButton = new JButton("+");
plusButton.setBounds(159, 45, 41, 25);
plusButton.setFocusable(false);
plusButton.setBackground(Color.WHITE);
plusButton.addActionListener(this);
minusButton = new JButton("-");
minusButton.setBounds(159, 75, 41, 25);
minusButton.setFocusable(false);
minusButton.setBackground(Color.WHITE);
minusButton.addActionListener(this);
add(plusButton);
add(minusButton);
}
@Override
public void actionPerformed(ActionEvent evnt) {
Object source = evnt.getSource();
if (source == plusButton) {
q++;
} else if (source == minusButton) {
q--;
}
// если будет больше кнопок, то может быть не для каждой надо вызывать repaint (просто перенести в каждый иф, где надо перерисовать)
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(String.valueOf(q), 140, 80);
}
}
}