New to SWING asking for help

There are two windowspanel. In different classes, the buttons are separate, the input fields are separate.

public class WindowFrame extends JFrame { WindowFrame(){ WindowPanel windowPanel = new WindowPanel(); WindowPanel2 windowPanel2 = new WindowPanel2(); this.setPreferredSize(new Dimension (400,600)); this.add(windowPanel); this.add(windowPanel2); this.setFocusable(true); this.pack(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); this.setTitle("Calculator"); } } public class WindowPanel extends JPanel { TextField textField1; TextField textField2; TextField textField3; WindowPanel(){ this.setLayout(null); Label label1 = new Label(); this.add(label1); label1.setText("First digit"); label1.setBounds(50, 50, 200, 20); TextField textField1 = new TextField(); textField1.setBounds(50, 70, 200, 30); this.add(textField1); } public class WindowPanel2 extends JPanel { WindowPanel2(){ this.setLayout(new GridLayout(2, 2)); ButtonListener1 bl1 = new ButtonListener1(this); Button button1 = new Button("+"); this.add(button1); button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { float first = Float.parseFloat(WindowPanel.textField1.getText()); float second = Float.parseFloat(WindowPanel.textField2.getText()); float result = first + second; WindowPanel.textField1.setText(""); WindowPanel.textField2.setText(""); WindowPanel.textField3.setText(Float.toString(result)); } }); } 

At startup, it produces an NPE error, that is, it does not get the value of the "textField" field.

What am I wrong?

    1 answer 1

    Honestly, I don’t understand how this code was compiled at all, since you are trying to access the non-static fields of the WindowPanel class via the class name:

     float first = Float.parseFloat(WindowPanel.textField1.getText()); 

    The error at least is that when accessing the interface elements you are trying to refer to the fields of the WindowPanel class, and not to the fields of the windowPanel class WindowPanel object you created.

    UPD . And as suggested in the comments, in the WindowPanel() constructor you do not initialize the class fields: the local variable of the TextField textField1 constructor TextField textField1 hides the class field of the same name, and the other two fields you do not initialize at all.