简体   繁体   中英

Java Swing Access Class Variables From Button

So in my Java Swing application, I need a button ActionListener to be able to access variables outside of its scope like so:

int x = 13;

JButton btn = new JButton("New Button");
btn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println(x);
    }
});

but I get a variable out of scope error. How can I access it?

The action listener is an anonymous inner class. This means that it can only use final variables from an outer scope. So, either declare x as final or pass it into the class some other way.

This should work:

final int x = 13;

JButton btn = new JButton("New Button");
    btn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println(x);
    }
});

Alternatively, see Pass variables to ActionListener in Java for some other options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM