简体   繁体   English

将JButton actionListener传递给另一个Java类时出现Nullpointer异常

[英]Nullpointer Exception when passing JButton actionListener to another Java Class

I have two classes ( Main_Menu and CancelListener ). 我有两个类( Main_MenuCancelListener )。 When i called an instance of my CancelListener to use the proper actionPerformed method, i get a NullPointerException . 当我调用CancelListener的实例以使用适当的actionPerformed方法时,我得到了NullPointerException

In my MainMenu.java class, i declare the button like this: 在我的MainMenu.java类中,我这样声明按钮:

JButton button = new JButton();
button.addActionListener(new CancelListener());

Here is my CancelListener() class. 这是我的CancelListener()类。

class CancelListener implements ActionListener {

    private Main_Menu menu;
    public JPanel mpan;

    public CancelListener() {
    }

    @Override
    public void actionPerformed(ActionEvent ae) {


        System.out.println("worked");
        try {

            CardLayout c1 = (CardLayout) (menu.MainPanel.getLayout());
            c1.show(menu.MainPanel, "AppPanel");
        } catch (Exception e) {

            System.out.println("Exception here " + e);
        }
    }
}

Further Information: MainPanel is a JPanel with a CardLayout structure. 进一步的信息: MainPanel是具有CardLayout结构的JPanel On the Cancel Button, i want to show a particular Panel. 在“取消”按钮上,我要显示特定的面板。 I wanted to separate my button view class from the button logic? 我想将按钮视图类与按钮逻辑分开吗? it works when i dont use a separate class. 当我不使用单独的类时,它可以工作。

You need the menu variable to be set: 您需要设置menu变量:

In CancelListener class: 在CancelListener类中:

private Main_Menu menu;

public CancelListener(Main_Menu menu) {
    this.menu = menu;
}

Then, when constructing: 然后,在构造时:

button.addActionListener(new CancelListener(this));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM