简体   繁体   中英

Trying to reference text from a JTextField when clicking on a JButton

I have (basically) the following code

JTextField input = new JTextField(20);
JButton calculate = new JButton("calculate");
calculate.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent event){
        String test = new String(input.getText());

        }
});

and basically my goal is to do something with the text from the textfield "input" when the button is clicked. However I get

"Cannot refer to the non-final local variable input defined in an enclosing scope"

How do I access the text in "input" when the button is clicked, without this error?

You could mark the input field as final , for example

final JTextField input = new JTextField(20);
JButton calculate = new JButton("calculate");
calculate.addActionListener(new ActionListener(){
    String test = input.getText();
});

But I'd prefer to make the field an instance field, but that's me. See Understanding Class Memembers for more details

I guess your field declaration inside some method.

Make these declaration in the class scope. Not in any method like constructor or others.

Declare them as a class property as like:

JTextField input;
JButton calculate;

then initialize them where you want to

input = new JTextField(20);
calculate = new JButton("calculate");

If you want to keep that JTextField input as local variable then you have to make it final to get access from the ActionListener .

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