看看其他答案,我完全按照他们的说法,但我只是不断收到nullPointerException错误。我有4个类,下面是2个类,一个GUI类和主菜单类。 Main管理卡片布局,我想在Insert类中使用一个按钮将“Active”卡更改为主菜单类。
主:
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 :(得分:0)
lListener = new LogoutListener(null);
你的LogoutListener接受你的Main-class,但你给他null。当然你会得到一个NullPointerException(至少在你的logoutButton上点击)。
答案 1 :(得分:0)
下一行中的问题:
lListener = new LogoutListener(null);
main.swapView("mm");
您需要引用Main
课程,而不是null
。由于main
中的LogoutListener
为空,您抓住NPE
。
简单的解决方案是在构造函数的帮助下将Main
的引用转移到Insert
,然后将其转移到LogoutListener
。