I have a JButton in my program, defined as follows (more or less)
public class MyTester{
public static void main(String[] args)
{
int counter = 0;
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
startButton.doSomething()
counter++;
}
}
);
}
}
I want to be able to count the number of times that the button is clicked. Problem is, I can’t declare a counter and then increment it after the call to .doSomething(), because the variable has to be final for me to reference it in the inner class.
Is there a way to do this, other than creating my own wrapper class with its own .increment() method?
Depending on threading situation, you can move the variable to the enclosing class. But this can go very wrong if you invoke
foo()several times, since that will use the same counter.