自定义控件出现意外的运行时错误(Java Swing GUI)

时间:2015-02-20 16:50:26

标签: java swing jframe jpanel jcomponent

所以我正在尝试建立一个GUI。但我似乎无法找到我得到的错误。这是我的错误:

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)

这是我的代码:

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);
 }

}

对于缩进很抱歉但有人能告诉我为什么我不能运行此代码吗?

3 个答案:

答案 0 :(得分:3)

你应该致电:

textfield1 = new JTextField();

如果指定了字符数,

textfield1 = new JTextField(amount);

答案 1 :(得分:3)

你错过了这些变量的实例化。

private JTextField textField1 = new JTextField(""), textField2 = new JTextField(""), textField3 = new JTextField("");
private JButton calculateButton = new JButton ("Text of Button");
private JTextArea textArea1 = new JTextArea("");

当你打电话给他们时,他们是null。这就是你犯这个错误的原因。

答案 2 :(得分:2)

您正在使用变量textFieldX和textArea而不进行实例化。

在globaltest方法中,添加实例

textField1 = new JTextField() ......等等!你应该摆脱那个错误