When is try to get an input from the textfield it gives me an error message:
"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException:
Cannot invoke "javax.swing.JTextField.getText()" because
"this.textField2" is null"
I have tried everything that I am aware and I'm expecting to set the value of an integer using the:
x = textField1.getText();
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.*;
import javax.swing.*;
public class Frame extends JFrame implements ActionListener
{
JTextField textField1;
JTextField textField2;
JTextField textField3;
JButton button;
int[] newArr = new int[2];
int num1, num2, num3;
//we need to declare button and text field outside constructor so they become global
Frame()
{
//Text box
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setPreferredSize(new Dimension(500,100));
//Text field 1
JTextField textField1 = new JTextField();
textField1.setPreferredSize(new Dimension(40,40));
this.add(textField1);
//Text field 2
JTextField textField2 = new JTextField();
textField2.setPreferredSize(new Dimension(40,40));
this.add(textField2);
//Text field 3
JTextField textField3 = new JTextField();
textField3.setPreferredSize(new Dimension(40,40));
this.add(textField3);
//Button 1
button = new JButton("Submit Guess");
button.addActionListener(this);
this.add(button);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e .getSource() == button)//if source of event comes from button...
{
newArr[0] = Integer.parseInt(textField1.getText());
newArr[1] = Integer.parseInt(textField2.getText());
newArr[2] = Integer.parseInt(textField3.getText());
System.out.println(newArr[0] + newArr[1] + newArr[2]);
}
}
}