1
我希望能夠將AcitonListener添加到另一個類的JButton中,以保持代碼整潔。唯一的問題是它在嘗試添加它時會引發NullPointerException。從另一個類向JButton添加一個ActionListener會給出一個NullPointerException?
我通過Handler類添加了ActionListener,它被定義爲'h'。
在我Display類:
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;
}
}
這裏是我的處理程序類,包括主要干將。它有助於使一切有很多更簡單的通過在處理程序類中的所有干將,而不是讓他們在多個不同類別展開:
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」(和**在哪裏**是它*聲明*)?另外,'calculate'聲明在哪裏***和*** *初始化*?最後,**如何**這是不同於[什麼是NullPointerException,我該如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and如何做我修復它) –
@ElliottFrisch我明白什麼是NullPointerException。我無法弄清楚我要去哪裏錯了。 計算和h對象只是連接到其他類的方法。 它們被定義爲: private Handler h; 私人CalculateActionListener計算; 它們每個都是在它們正在使用的類中定義的。 –
考慮提供一個[runnable示例](https://stackoverflow.com/help/mcve),它演示了您的問題。這不是代碼轉儲,而是您正在做的事情的一個例子,它突出了您遇到的問題。這會減少混淆和更好的反應 – MadProgrammer