0

我为我的 CRUD 程序编写了一个 gui,当我想运行它时,我得到:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at gui.guimain$1.run(guimain.java:477)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

这就是 NPE 来自的代码:

public static void main(String[] args){
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run(){
                maingui.showStart();// thats the line with the Exception
        }
    });
}

这就是 showStart() 方法:

public void showStart(){
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.getContentPane().removeAll();
    tabstructure.removeAll();
    Produkt filter=new Produkt();

    JPanel P=new JPanel();
    P=Produktgui(0, filter);
    JPanel R=new JPanel();
    R=Billgui(0);
    JPanel nR=new JPanel();
    nR=Billgui(0);

    tabstructure.addTab("e", P);
    tabstructure.addTab("Bills", R);
    tabstructure.addTab("Pay bill", nR);
    mainFrame.getContentPane().add(tabstructure);
    mainFrame.validate();
    mainFrame.repaint();
    mainFrame.pack();
    mainFrame.setVisible(true);
}

为什么我得到一个NullPointerException

4

3 回答 3

6

您将必须创建一个MainGui.

public static void main(String[] args) {
    final MainGui maingui = new MainGui();
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run(){
                maingui.showStart();// thats the line with the Exception
        }
    });
}
于 2012-10-03T13:06:05.453 回答
5

因为你调用方法的东西是null.

仔细查看错误信息。它说异常发生在第 477 行guimain.java

那时,mainguinull

于 2012-10-03T13:05:06.690 回答
5

您必须先实例化对象,然后才能对其调用方法。在这种情况下,maingui尚未实例化。

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            MainGUI maingui = new MainGUI();
            maingui.showStart();
        }
    });
}
于 2012-10-03T13:06:15.573 回答