CIS 35A: Introduction to Java Programming

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

Events

Events
Handle events
Separate event listeners

How to implement separate event listeners for each event

  • You can eliminate the code in the event listener class that determines the event source by creating a separate listener class for each component that raises the event.
  • In that case, you simply register an instance of each event listener class with the appropriate event source.

Code that implements separate listeners for each event

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

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

        exitButton = new JButton("Exit");
        exitButton.addActionListener(new ExitListener());
        this.add(exitButton);
    }

    class CalculateListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            calculateButton.setText("Clicked!");
        }
    }

    class ExitListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }
}
Previous | Java event model | Two types | Structure event handling code | Panel | Separate class | Inner class | Separate event listeners | Anonymous inner classes | Next