2014-02-25 18 views
-1

看看其他答案,我完全按照他们的说法,但我只是不断收到nullPointerException错误。我有4个类,下面的2个,一个GUI类和主菜单类。主要管理卡布局,我希望Insert类中的按钮将“活动”卡更改为主菜单类。Java,改变另一个类的活动卡

主营:

public class Main extends JPanel implements ChooserListener{ 
    MainMenu mm; 
    Insert InsertCustomer; 
    public JPanel mPanel;  
    CardLayout cl; 

    private String c; 

     public Main(){ 
      super(); 

      //add mPanel, set to CardLayout and add the Main 
      mPanel = new JPanel(); 
      this.add(mPanel); 
      cl = new CardLayout(); 
      mPanel.setLayout(cl); 
      //add classes 
      mm = new MainMenu(this);   
      InsertCustomer = new Insert();   
      //add classes to mPanel 
      mPanel.add(mm, "mm"); 
      mPanel.add(InsertCustomer, "InsertCustomer"); 
     } 

     public void tell(Object o) { 
      c = o.toString(); 
      cl.show(mPanel, c); 
     } 

     public void swapView(String key) { 
      CardLayout cl = (CardLayout)(mPanel.getLayout()); 
      cl.show(mPanel, key); 
     } 
    } 

插入:

public class Insert extends JPanel{ 

    private JButton logoutbutton; 
    private LogoutListener lListener; 

    public Insert() { 
     super(); 

     //BUTTONS 
     //logout button 
     JButton logoutbutton = new JButton("Main Menu"); 
     this.add(logoutbutton); 
     lListener = new LogoutListener(null); 
     logoutbutton.addActionListener(lListener); 
    } 

    private class LogoutListener implements ActionListener{ 
     private Main main; 

     public LogoutListener(Main main){ 
      this.main = main; 
     } 

     public void actionPerformed(ActionEvent e) { 
      main.swapView("mm"); 
     } 
    } 
} 
+0

你可以在这里添加stackTrace吗? – ItachiUchiha

+0

你在哪里有NullPointerException? –

+0

一个非常简单的空指针异常。这个问题不可能在将来帮助任何人。 –

回答

0
lListener = new LogoutListener(null); 

你LogoutListener需要你的主类,但你给他空。当然,你会得到一个NullPointerException(至少在你的注销按钮单击)。

0

你的下一行的问题:

lListener = new LogoutListener(null); 

main.swapView("mm"); 

你需要把引用您的Main类,而不是null为你做。由于您的mainLogoutListener为空,您可以捕获NPE

简单的办法就是你Main的参考与构造的帮助下转移到Insert,然后转移,为LogoutListener