CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Swing

Swing
Panels, buttons and events
Handle button events

How to handle an action event

  1. Specify that the class that contains the button implements the ActionListener interface:
  2. class FutureValuePanel extends JPanel implements ActionListener
  3. Add an ActionListener object to the button by calling the addActionListener method:
  4. exitButton.addActionListener(this);
  5. Implement the ActionListener interface by coding the actionPerformed method:
  6. 
    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!");
    }
}
Previous | Add a panel to a frame | Add buttons to a panel | Handle button events | Next