开发者

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 i开发者_C百科s: " + 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...


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.


JButton letterButton 

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜