I have a very simple GUI app. It only consists of a button and a label to display how many times that button has been clicked. I implemented it as follows:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Scratch {
public static void main(String[] args) {
JFrame frame = new JFrame("Click Counter");
frame.setSize(400,250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton button = new JButton("Click Here");
final int count = 0;
final JLabel label = new JLabel("Click Count: 0");
panel.add(button);
panel.add(label);
frame.add(panel):
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
count++; // Error
String s = label.getText();
label.setText("Click Count: " + count);
}
});
frame.setVisible(true);
}
}
The problem is with the count
variable. If I don't declare it as final, I cannot access it inside the anonymous class. If I do however, I cannot modify it. So what do I do? I really prefer creating actionlistener classes as anonymous classes as opposed to creating multiple classes in a single .java file.