newbie
newbie

Reputation: 14950

Problem in Disabling JButton in Java

Good day!

I want to disable a button once I click it. My code is as follows..

for (char buttonChar = 'a'; buttonChar <= 'z'; buttonChar++) {
        String buttonText = String.valueOf(buttonChar);
        JButton letterButton = new JButton(buttonText);
        letterButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String actionCommand = e.getActionCommand();
                System.out.println("actionCommand is: " + actionCommand);
                letterButton.setEnabled(false);    //I disable the button here
            }
});

But an error appears: local variable letter Button is accessed from the inner class; needs to be declared final.. What does it mean? how can i resolve the issue? Thank you...

Upvotes: 2

Views: 335

Answers (2)

user467871
user467871

Reputation:

JButton letterButton 

should be final because only final variables or class fields (private/public) accessible in anonymous classes. Have a look at this topic

Upvotes: 1

aioobe
aioobe

Reputation: 420951

It doesn't really have to do with disabling the button, but rather accessing the reference to the button at all.

You need to declare the letterButton as final. That is, change from

JButton letterButton = new ...

to this

final JButton letterButton = new ...

Here is a good explanation on why it needs to be final: Why inner class can access only final variable?

The reason is basically the following: Your local variables can not be touched by other threads. The code of the ActionListener will possibly be executed by another thread. By making the variable final, you're basically transforming it to a value. This value can then be read by several threads concurrently.

Upvotes: 2

Related Questions