I want to be able to add an AcitonListener to a JButton from another class just to keep the code neat. The only problem is that it brings up a NullPointerException when trying to add it.
I'm adding the ActionListener through the Handler class which is defined as 'h'.
In my Display class:
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;
}
}
Here's my Handler class that includes mostly getters. It helps make everything a lot more simple by having all the getters in the Handler class instead of having them spread out in multiple different classes:
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();
}
}
And finally, here's my CalculateActionListener class which contains the actual 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;
}
}
Note Imports were removed but are there in the actually code. Imports are not the problem.