Accessing Variable within JButton ActionListener

冷暖自知 提交于 2019-12-24 09:29:32

问题


This seems like a very simple problem, but I'm having a lot of trouble figuring out how to deal with it.

Sample Scenario:

    final int number = 0;

    JFrame frame = new JFrame();
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
    frame.setSize(400, 400); 

    final JTextArea text = new JTextArea();
    frame.add(text, BorderLayout.NORTH);

    JButton button = new JButton(number + ""); 
    button.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent arg0) { 
        number++; // Error is on this line
        text.setText(number + "");
    }});
    frame.add(button, BorderLayout.SOUTH);

I really have no idea where to go.


回答1:


If you declared number as final, you cannot modified its value. You must remove the final modificator.

Then, you can access to that variable via:

public class Scenario {
    private int number;

    public Scenario() {
        JButton button = new JButton(number + "");
        button.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent arg0) { 
                Scenario.this.number++;
                text.setText(Scenario.this.number + "");
            }
        });
    }
}

The notation "ClassName.this" allow you to access to the object of a class where you are in.

Keep atention in when you use "number" first time, -new JButton(number)-, you can access to number directly, because you are in Scenario scope. But when you use it inside your ActionListener, you are in your ActionListener scope instead of Scenario scope. That is why you cannot see the variable "number" directly inside of your action listener and you have to access to the instance of Scenario where you are in. This can be done by Scenario.this




回答2:


The fastest solution would be to declare number as static, and reference it using the name of your class.

Alternatively you can make a class that implements ActionListener, and pass number and text into it's constructor.



来源:https://stackoverflow.com/questions/19228436/accessing-variable-within-jbutton-actionlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!