Search code examples
javaeclipseactionlistener

How can I get an Integer from an ActionListener?


I'm new to java and I have the following problem: I added an ActionListener to a button and I want to access a number from it, but it doesn't work the way I did. I seached for it but I couldn't find an answer. The code looks like this now:

public class example extends JPanel{

    int text;

    public example(){

        JButton button = new JButton("x");
        JTextField textField = new JTextField();

        add(textField);
        add(button);

        ActionListener al = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                text = Integer.parseInt(textField.getText());
            }
        }

        button.addActionListener(al);
        system.out.println(text);
    }
}

Solution

  • Problem is with your logic. You added the ActionListener to the button. Hence whenever you hit the button, value of text is the value of textField. But initial value of text is null. In your code, after adding the ActionListener, value of text is printed. You may want to change your ActionListener like this:

    ActionListener al = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            text = textField.getText();
            someFun();
            system.out.println(text);
        }
    }
    

    To get integer from string, use Integer.parseInt() function:

    void someFun() {
        int num = Integer.parseInt(text);
        ... // Do whatever you want to do
    }