CIS 35A: Introduction to Java Programming

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

Events

Events
Handle events
Separate class

How to implement an event listener as a separate class

  • If you implement a listener as a separate class, you'll need to provide a way for the listener class to access the source components and any other panel components that are required to respond to the event.
  • One way to do that is to pass the panel to the constructor of the listener class and declare the components that need to be referred to as public.

Code for a panel that uses a separate listener class: The panel class

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

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

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

Code for a panel that uses a separate listener class: The listener class

class FutureValueActionListener implements ActionListener
{
    private FutureValuePanel panel;

    public FutureValueActionListener(FutureValuePanel p)
    {
        this.panel = p;
    }

    public void actionPerformed(ActionEvent e)
    {
        Object source = e.getSource();
        if (source == panel.exitButton)
            System.exit(0);
        else if (source == panel.calculateButton)
            panel.calculateButton.setText("Clicked!");
    }
}
Previous | Java event model | Two types | Structure event handling | Panel | Separate class | Inner class | Separate event listeners | Anonymous inner classes | Next