CIS 35A: Introduction to Java Programming

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

Events

Events
Handle events
Panel

Code for a panel that implements the ActionListener interface

class FutureValuePanel extends JPanel implements ActionListener
{
    private JButton calculateButton;
    private JButton exitButton;

    public FutureValuePanel()
    {
        calculateButton = new JButton("Calculate");
        calculateButton.addActionListener(this);
        this.add(calculateButton);

        exitButton = new JButton("Exit");
        exitButton.addActionListener(this);
        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!");
    }
}

Notes

  • The easiest way to implement a listener interface is in the class that defines the panel or frame that contains the components that generate the events.
  • When the panel or frame class itself implements the listener, you can specify the this keyword as the parameter to the method that registers the listener.
Previous | Java event model | Two types | Structure event handling code | Panel | Separate class | Inner class | Separate event listeners | Anonymous inner classes | Next