CIS 35A: Introduction to Java Programming

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

Events

Events
Handle events
Anonymous inner classes

The syntax for creating an anonymous class for an event listener

new ListenerInterface() { class-body }

How to implement event listeners as anonymous inner classes

  • An anonymous inner class is a class that is both declared and instantiated in one statement.
  • Anonymous inner classes are often used as event listeners.
  • Anonymous inner classes force you to mix the code that creates a panel with the code that responds to the panel's events. So they should be used for only the simplest event listeners.

Code that implements event listeners as anonymous classes

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

    public FutureValuePanel()
    {
        calculateButton = new JButton("Calculate");
        calculateButton.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    calculateButton.setText("Clicked!");
                }
            } );
        this.add(calculateButton);

        exitButton = new JButton("Exit");
        exitButton.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    System.exit(0);
                }
            } );
        this.add(exitButton);
    }
}
Previous | Java event model | Two types | Structure event handling code | Panel | Separate class | Inner class | Separate event listeners | Anonymous inner classes | Next