Reputation: 59
So I'm currently trying to build up a GUI. But I can't seem to be able to find the error I get. This is my error:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at GlobalTest.<init>(GlobalTest.java:41)
at GlobalTest.main(GlobalTest.java:7)
And here is my code:
import java.awt.*;
import javax.swing.*;
public class GlobalTest extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("Global Test");
window.setContentPane(new GlobalTest());
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation((screensize.width - window.getWidth()) / 2,
(screensize.height - window.getHeight()) / 2);
window.setVisible(true);
}
//---------------------------------------------------------------------------------------------------
private JTextField textField1, textField2, textField3;
private JButton calculateButton;
private JTextArea textArea1;
public GlobalTest() {
setLayout(new GridLayout(1,3,3,3));
setBackground(Color.BLUE);
setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
add(panel1);
add(panel2);
add(panel3);
panel1.setLayout(new GridLayout(3,1,2,2));
panel1.setBorder(BorderFactory.createEmptyBorder(0,5,0,5));
panel1.add(textField1);
panel1.add(textField2);
panel1.add(textField3);
panel2.setBorder(BorderFactory.createEmptyBorder(0,5,0,5));
panel2.add(textArea1);
panel2.setPreferredSize(new Dimension(200,200));
panel3.setBorder(BorderFactory.createEmptyBorder(0,5,0,5));
panel3.add(calculateButton);
}
}
So sorry for the indenting but can anyone tell me why I can't run this code?
Upvotes: 1
Views: 105
Reputation: 36
You are using your variables textFieldX and textArea without instanciating them.
In your globaltest method, add your instanciations
textField1 = new JTextField()
...etc ! and you should get rid of that error
Upvotes: 2
Reputation: 11163
You missed instanciating these variables.
private JTextField textField1 = new JTextField(""), textField2 = new JTextField(""), textField3 = new JTextField("");
private JButton calculateButton = new JButton ("Text of Button");
private JTextArea textArea1 = new JTextArea("");
So they were null
when you were calling them. That's why you got that error.
Upvotes: 3
Reputation: 7719
You should call:
textfield1 = new JTextField();
if the amount of characters is specified,
textfield1 = new JTextField(amount);
Upvotes: 3