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]);
}
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
Here's a revised GUI:
Creating a
JPanelto place in theJFramehelps to separate your concerns and focus on one part of the GUI at a time.Using a
JFrameis better than extending aJFrame. You shouldn't extend any Java class unless you intend to override one or more of the class methods.A Java array has to be long enough to hold all of the elements of the array.
Here's the complete runnable code.