Swing
Panels, buttons and events
Handle button events
How to handle an action event
- Specify that the class that contains the button implements the ActionListener interface:
- Add an ActionListener object to the button by calling the addActionListener method:
- Implement the ActionListener interface by coding the actionPerformed method:
class FutureValuePanel extends JPanel implements ActionListener
exitButton.addActionListener(this);
public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == exitButton) System.exit(0); }
A panel class that handles two action events
class FutureValuePanel extends JPanel implements ActionListener { private JButton calculateButton; private JButton exitButton; public FutureValuePanel() { calculateButton = new JButton("Calculate"); calculateButton.addActionListener(this); // add an action listener this.add(calculateButton); exitButton = new JButton("Exit"); exitButton.addActionListener(this); // add an action listener this.add(exitButton); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == exitButton) System.exit(0); else if (source == calculateButton) calculateButton.setText("Clicked!"); } }