运行GUI时出现NullPointerException错误

时间:2014-11-26 10:37:13

标签: java user-interface nullpointerexception

我对GUI的知识有限。我正在尝试创建一个非常基本的GUI,并具有以下内容:

public class Controller {

    // variables   
    private JFrame ACMEFrame;
    private JPanel contentPane;
    private JPanel contentPanel;
    private JPanel detailsPanel;
    private JPanel buttonPanel;
    private JLabel label;
    private JComboBox box;

    private JButton ok;
    private JButton quit;


    // constructor
    public Controller() {
        handleAddCruiseToShip();
    }

    public final void handleAddCruiseToShip() {

        ACMEFrame = new JFrame("Assign Cruise to Ship"); // name of frame
        ACMEFrame.setSize(600, 400); // size of JFrame
        ACMEFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // exit JFrame on close

        contentPanel = new JPanel();
        contentPanel.setBackground(Color.GREEN);

        quit = new JButton("Quit");
        ok = new JButton("Ok");

        detailsPanel.add(quit);
        detailsPanel.add(ok);

        ACMEFrame.add(detailsPanel);

        ACMEFrame.pack();
        ACMEFrame.setVisible(true);

    }
}

但是,在运行测试类(guiTest)时,我遇到了以下错误:

Exception in thread "main" java.lang.NullPointerException
    at Controller.AddCruiseToShip(Controller.java:42)
    at Controller.<init>(Controller.java:26)
    at guiTest.main(guiTest.java:10)

以前,我能够运行测试类并显示GUI,但是,现在我遇到了错误。

这是我的guiTest课程:

public class guiTest {

public static void main (String args []){

    new Controller();
}

}

我如何克服这个问题?

谢谢。

1 个答案:

答案 0 :(得分:0)

您永远不会实例化您的detailsPanel。然后添加按钮并将其添加到ACMEFrame。这导致空指针异常,因为您只声明了它。您需要像使用contentPanel一样添加这样的内容:

detailsPanel = new JPanel();

就此而言,自从你创建了它以后,可以对你的contentPanel做一些事情......