Events
Handle events
Separate event listeners
How to implement separate event listeners for each event
- You can eliminate the code in the event listener class that determines the event source by creating a separate listener class for each component that raises the event.
- In that case, you simply register an instance of each event listener class with the appropriate event source.
Code that implements separate listeners for each event
class FutureValuePanel extends JPanel { private JButton calculateButton; private JButton exitButton; public FutureValuePanel() { calculateButton = new JButton("Calculate"); calculateButton.addActionListener(new CalculateListener()); this.add(calculateButton); exitButton = new JButton("Exit"); exitButton.addActionListener(new ExitListener()); this.add(exitButton); } class CalculateListener implements ActionListener { public void actionPerformed(ActionEvent e) { calculateButton.setText("Clicked!"); } } class ExitListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } }