Search code examples
javaswinginputpaneljtextfield

How to: get input from JTextField after button is pressed


I am fairly new to Java and just wanted to ask about ActionListener method. I've created a GUI and in one panel I want to ask the user to input values of x and press submit. It looks like this: f(x)= [input field] - [input field] ^2 (submit button) I am lost and don't know what to put in ActionPerformed method to get the values that user inputs (also the method in which I created the panel, text fields etc is private if that's relevant )

I have already tried x1.getText(), but it seems like it can't access the variable as the JPanel method is private, and ActionPerformed is public


private JPanel panel2() 
    {    
        inputPanel.setLayout(new FlowLayout());

        JTextField  x1 = new JTextField();
        JTextField  x2 = new JTextField();

        JLabel f = new JLabel ("F(x)= ");
        JLabel f2= new JLabel (" - ");
        JLabel f3 = new JLabel (" ^2 ");
        JButton submit1 = new JButton("Submit values");

        submit1.addActionListener(this);

        inputPanel.add(f);
        inputPanel.add(x1);
        inputPanel.add(f2);
        inputPanel.add(x2);
        inputPanel.add(f3);
        inputPanel.add(submit1);
      }
    {
        if("submit1".equals(e.getActionCommand()))
        {
           // and that's where I get lost

        }
    } 

Solution

  • I am inferring by your discription that panel2 is a method and both JTextfields x1 and x2 are local variables of method panel2 which won't be accessible outside it.

    You will need to declare the x1 and x2 globally and if you want them to be private, associate getters and setters with them and use it in the actionperformed method.