next up previous contents
Next: The event queue Up: Some examples of event Previous: A button   Contents

Three buttons

Suppose we want to have a panel with three buttons, labelled Red, Blue and Yellow, so that clicking each button results in the background colour changing to the appropriate colour. We can modify the earlier ButtonPanel to contain three buttons.

The ActionListener associated with each button has to be able to inform the ButtonPanel to change its background colour. The simplest solution is to make the ButtonPanel itself the ActionListener for all three buttons. However, we now have a single ActionListener handling events from multiple sources. In ActionPerformed, we can use the getSource() method to find out the source of the event and then take appropriate action.

Here is the revised code for ButtonPanel for this example. The code for ButtonFrame does not change.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonPanel extends JPanel implements ActionListener{

    private JButton yellowButton;    // Panel has three buttons
    private JButton blueButton;
    private JButton redButton; 

    public ButtonPanel(){
        yellowButton = new JButton("Yellow");
        blueButton = new JButton("Blue");
        redButton = new JButton("Red");

        yellowButton.addActionListener(this);  // ButtonPanel is the
        blueButton.addActionListener(this);    //   listener for all
        redButton.addActionListener(this);     //   three buttons

        add(yellowButton);
        add(blueButton);
        add(redButton);
    }
        
    public void actionPerformed(ActionEvent evt){
        Object source = evt.getSource();       // Find the source of the
                                               //   event
        Color color = getBackground();         // Get current background
                                               //   colour

        if (source == yellowButton) color = Color.yellow;
        else if (source == blueButton) color = Color.blue;
        else if (source == redButton) color = Color.red;

        setBackground(color);
        repaint();
    }
}

Some more examples can be found in Appendix A.



Madhavan Mukund 2004-04-29