Actions for buttons

Please refer to Handling Events We learned interface mainly for understanding how to create Swing applications that response to user input (like clicking on button).

What happen what you click a JButton

We will concentrate on JButton first.
  1. When you click on the JButton, the button fires an ActionEvent.
  2. The button registers with some ActionListener before through the add(ActionListener actionListener) method.
  3. When an action event is fired. It invokes the actionPerformed (ActionEvent e) method of the ActionListener(s).
    You don't call the method explicitly but it is implicitly called by computer.

What is an ActionListener?

An ActionListener is an interface in package java.awt.event.
It has only one method
void actionPerformed(ActionEvent e) 

Question

What method should you override when you implemnts ActionListener ?

To implements an ActionListener, use
import java.awt.event.*;

public void class MyClass implements ActionListener {
    public void actionPerformed(ActionEvent e) {
       // your code
    }
}

What is an ActionEvent?

How to register an ActionListener

Use button.addActionListener(actionListener).

ButtonTest.java

We are going to write a program react to user's clicks. The class extends JFrame, when you click on the button, the counter is increased by 1.
You can get the program here.
buttontest.gif
   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*; 
   4:
   5:public class ButtonTest extends JFrame implements ActionListener {
   6:    private JLabel countLabel;
   7:    private JButton button;
   8:    private int count = 0; 
   9:    private Container contentPane;
  10:    public ButtonTest() {
  11:        contentPane = getContentPane();
  12:        contentPane.setLayout(new GridLayout(2,1));
  13:        // change the count to string. alignment is center
  14:        countLabel = new JLabel(Integer.toString(count), JLabel.CENTER);
  15:        button = new JButton("Click me");
  16:        contentPane.add(countLabel);
  17:        contentPane.add(button);
  18:        // the class is an action listener
  19:        button.addActionListener(this);
  20:    }
  21:    
  22:    // what happens after you click the button
  23:    public void actionPerformed(ActionEvent e) {
  24:        count++;
  25:        countLabel.setText(Integer.toString(count));
  26:    }
  27:    
  28:   public static void main(String[] args) {
  29:        ButtonTest f = new ButtonTest();
  30:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  31:        f.pack();
  32:        f.setVisible(true);
  33:    }
  34:}     

Highlight of the program

Line 5 : implements has almost the exact meaning as extends. We have to override actionPerformed method inherited from the class ActionListener.
You can create another class to implement ActionListener, but it is more convenient to implement on the original class. We don't have to pass the states to the extra class.
Line 19 : addActionListener to the button. ButtonTest "extends" ActionListener, so it itself (this) is an ActionListener.
Line 23 - Line 26 : actionPerformed method. Describe the reaction of the class when the user clicks on the button.

ButtonTest2.java

You can get the program here.
cat
cat.jpg
dog
dog.jpg
bird
cat.jpg
horse
horse.jpg

There are 4 buttons labeled cat, dog, bird and horse on the top. When you click on a button, the corresponding animal picture shows up. The output of the program is :

buttontest2a.gif
After you click on the button labeled "cat"
buttontest2b.gif
After you click on the button labeled "bird"

   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:
   5:public class ButtonTest2 extends JFrame implements ActionListener {
   6:    // a panel to hold all the buttons
   7:    private JPanel buttonPanel = new JPanel(new GridLayout(1,0));
   8:    // a label to show pictures
   9:    private JLabel pictureLabel = new JLabel();
  10:    // a list of buttons, with the animal names on it
  11:    private JButton[] buttons =  { new JButton("cat"), 
  12:                                   new JButton("dog"),
  13:                                   new JButton("bird"),
  14:                                  new JButton("horse")};
  15:    // animal                             
  16:    private String animal = "cat";                                
  17:    private Container contentPane = getContentPane();
  18:    public ButtonTest2() {
  19:        // create the buttons and addActionListener to all the buttons
  20:        for(int i = 0; i < buttons.length; i++) {
  21:            buttonPanel.add(buttons[i]);
  22:            buttons[i].addActionListener(this);
  23:        }
  24:        contentPane.add(buttonPanel, BorderLayout.NORTH);
  25:        contentPane.add(pictureLabel);
  26:        pictureLabel.setHorizontalAlignment(JLabel.CENTER);
  27:        pictureLabel.setOpaque(true);
  28:        pictureLabel.setBackground(Color.yellow);
  29:        setLabelPicture(); // see below
  30:    }
  31:    
  32:    // set the icon of the pictureLabel
  33:    private void setLabelPicture() {
  34:        String filename = animal + ".jpg";
  35:        pictureLabel.setIcon(new ImageIcon(filename));
  36:    }
  37:    
  38:    public void actionPerformed(ActionEvent e) {
  39:        // return the text from the source.
  40:        animal = e.getActionCommand(); 
  41:        setLabelPicture();
  42:    }
  43:    
  44:    public static void main(String[] args) {
  45:        JFrame f = new ButtonTest2();
  46:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  47:        f.setSize(800,600);
  48:        f.setVisible(true);
  49:    }
  50:}
  51:
  52:                                   

Highlight

Line 21 : addActionListener to each button.
Line 38 - 42 : use getActionCommand() to get the animal name on the button.
Line 33 - 36 : set the icon of the pictureLabel for the given animal.

Summary