Events
Handle events
Inner class
How to implement an event listener as an inner class
- An inner class is a class that is contained within another class.
- An inner class has access to all of the members of its containing class. Because of that, inner classes are often used to implement event listeners.
Code that implements the listener as an inner class
class FutureValuePanel extends JPanel { private JButton calculateButton; private JButton exitButton; public FutureValuePanel() { ActionListener listener = new FutureValueActionListener(); calculateButton = new JButton("Calculate"); calculateButton.addActionListener(listener); this.add(calculateButton); exitButton = new JButton("Exit"); exitButton.addActionListener(listener); this.add(exitButton); } class FutureValueActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == exitButton) System.exit(0); else if (source == calculateButton) calculateButton.setText("Clicked!"); } } }