Java 将ActionListener从另一个类添加到JButton会产生NullPointerException吗?
我希望能够从另一个类向JButton添加AcitonListener,以保持代码整洁。唯一的问题是,它在尝试添加时会引发NullPointerException 我通过定义为“h”的处理程序类添加ActionListener 在我的显示类中:Java 将ActionListener从另一个类添加到JButton会产生NullPointerException吗?,java,swing,actionlistener,Java,Swing,Actionlistener,我希望能够从另一个类向JButton添加AcitonListener,以保持代码整洁。唯一的问题是,它在尝试添加时会引发NullPointerException 我通过定义为“h”的处理程序类添加ActionListener 在我的显示类中: public class Display { private Handler h; //My handler object private JFrame frame; private JButton btnCalculate;
public class Display {
private Handler h; //My handler object
private JFrame frame;
private JButton btnCalculate;
/**
* Launch the application.
*/
public static void createDisplay() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display window = new Display();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Display() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
btnCalculate = new JButton("Calculate");
btnCalculate.setBounds(66, 208, 89, 23);
btnCalculate.addActionListener(h.getCalculateListener()); //ActionListener is added here.
frame.add(btnCalculate);
}
//Getter for the JButton
public JButton getBtnCalculate() {
return btnCalculate;
}
}
这是我的处理程序类,它主要包括getter。通过将所有getter放在Handler类中,而不是将它们分散在多个不同的类中,这有助于使一切变得更加简单:
public class Handler {
private Display display; //My Display object
private CalculateActionListener calculate; //My CalculateActionListener object
public Handler(Display display, CalculateActionListener calculate) {
this.display = display;
this.calculate = calculate;
}
public JButton getButton() {
return display.getBtnCalculate();
}
public ActionListener getCalculateListener() {
return calculate.getCalculateListener();
}
}
最后,这里是我的CalculateActionListener类,它包含实际的ActionListener:
public class CalculateActionListener {
//Here's the actual ActionListener
private ActionListener calculateListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "WORKING!");
}
};
//Getter for my ActionListener
public ActionListener getCalculateListener() {
return calculateListener;
}
}
注意导入已删除,但实际代码中有。导入不是问题。您没有创建
处理程序的新实例。在使用h
之前,需要创建它的实例。在显示类构造函数中创建按钮之前添加一行。大概是这样的:
h = new Handler(this, new CalculateActionListener());
什么是h
(在哪里声明)?另外,calculate
在哪里声明和初始化?最后,这与@ElliottFrisch有何不同?我理解NullPointerException是什么。我只是不知道我哪里出了问题。calculate和h对象只是连接到其他类的方法。它们被定义为:私有处理器h;私有计算侦听器计算;它们都在被使用的类中定义。考虑提供一个演示你的问题的。这不是一个代码转储,而是您正在做的一个示例,它突出了您所遇到的问题。这将减少混乱和更好的响应