Home : Course Map : Chapter 7 : Java :
Button Event Handling
JavaTech
Course Map
Chapter 7

Introduction
Event Overview
Event Processing
Button Events
  Demo 1
 Demo 2
Mouse Events
  Demo3

More Components
  Demo 4  Demo 5
  Demo 6  Demo 7

LayoutManagers-1
  Demo 8     Demo 9
  Demo 10  Demo 11
  Demo 12

LayoutManagers-2
  Demo 13  Demo 14
  Demo 15  Demo 16
  Demo 17

Inner Classes
Anonymous Class
Adapter Classes
  Demo 18  Demo 19
Frames & Menus
  Demo 20  Demo 21
Exercises

    Supplements
AWT Components
  Button
     Demo 1
  Canvas
     Demo 2
  AWT GUI Demo
     Demo 3
Swing Dialogs
JOptionPane Dialog
  Demo 1
JDialog
  Demo 2
UI Enhancement: P1
  Demo 1   Demo 2
  Demo 3

UI Enhancement: P2
  Demo 1
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

Buttons provide the most common event generating components in user interfaces. Clicking on the button should initiate some action. In fact, the term action is used in the names for the button even handling machinery:

  • A button maintains a list of objects that implement the ActionListener interface.

  • When the button is pressed, it invokes the actionPerformed method for all of the ActionListener instances in its list.

  • ActionListener classes override the abstract actionPerformed method to perform the task for the button.

  • An ActionEvent object is passed as an argument of actionPerformed and from it you can extract information about the event such as which ActionListener initated the event.

  • To add an ActionListener instance to a button, invoke its addActionListener(ActionListener) method.

The following applet illustrates the above button event handling process. PictureButton_Applet2 implements the ActionListener interface and so provides a actionPerformed method.

An instance of a subclass of JButton is created and the applet is added to its actionListener list with the

    button.addActionListener(this);

statement.

Each time the button is pushed, the actionPerformed method is called and the Applet's showStatus method is invoked. This method displays a string on the status line of the browser (along the botton border for most browsers.)

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

/** Demonstrate event handling with two buttons. **/
public class PlainButtonApplet extends JApplet
                         implements ActionListener

{
  int fPushACount = 0;
  int fPushBCount = 0;

  /** Build the interface with two buttons. **/
  public void init () {
    Container content_pane = getContentPane ();
    content_pane.setLayout (new FlowLayout ());

    // Create an instance of JButton
    JButton button_a = new JButton ("A");

    // Create an instance of JButton
    JButton button_b = new JButton ("B");

    // Add this applet to each button's ActionListener list
    button_a.addActionListener (this);
    button_b.addActionListener (this);

    JPanel panel = new JPanel ();

    // Add the buttons to the content pane.
    content_pane.add (button_a);
    content_pane.add (button_b);

  } // client()

  /** Count each button click and post total on status line. **/
  public void actionPerformed (ActionEvent event) {

    String cmd = event.getActionCommand ();

    if ( cmd.equals ("A")){
        fPushACount++;
        showStatus (event.getActionCommand () +
                  " pushed " + fPushACount + " times");
    }else{
       fPushBCount++;
       showStatus (event.getActionCommand () +
                  " pushed " + fPushBCount + " times");
    }

  } // actionPerformed()

} // class PlainButtonApplet

Event Objects

The event classes provides information on the event that allow the listener to find out, for example, what component generated the event.

A button generates an ActionEvent, which as the following subclass structure:

java.lang.Object
   |
   +--java.util.EventObject
         |
         +--java.awt.AWTEvent
               |
               +--java.awt.event.ActionEvent

See the API Specifications for a list of the methods available from these classes but the most commonly used include

  • getSource() in EventObject - returns an instance of Object for the component that generated the event.
  • getActionCommand() in ActionEvent - returns the text for the JButton that generated the action.

Note that the ActionListener can register with more than one button. These methods provide the identity of the button that generated a particular event.

Below we modify the applet MultiPanelApplet.java discussed in the previous chapter. That applet displayed buttons, text fields, and a text area but had no functionality. In the applet MultiPanelWithEvents shown below, the buttons cause the two values in the text fields to be added or multiplied together and the result displayed in the JTextArea component.

The applet implements the ActionListener interface. We modify the ActionButtonsPanel class so that it takes an ActionListener reference in the constructor and adds the listener to the buttons. The InputsPanel class needs no modification. The actionPerformed() method in the applet grabs the two values from the text fields and carries out the desired operation by examining the action command string.

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

/** Demonstrate GUI building with multiple panels and event handling. **/
public class MultiPanelWithEvents extends JApplet
              implements ActionListener {

  InputsPanel fInputsPanel;
  JTextArea fTextOutput;

  /** Build the interface with InputsPanel and ActionButtonsPanel. **/
  public void init () {
    Container content_pane = getContentPane ();

    // Set the layout as before with 1 row of 3 columns
    // but now in one step.
    content_pane.setLayout (new GridLayout (1, 3));

    // First create a panel of buttons
    ActionButtonsPanel buttons_panel =
        new ActionButtonsPanel (this);

    // Next create a panel of input fields and labels
    fInputsPanel =
        new InputsPanel ("Input x ", "1.5",
                         "Input y ", "3.14");

    // Use a JTextArea for the output of the calculations.
    fTextOutput = new JTextArea ();
    fTextOutput.setBackground (Color.LIGHT_GRAY);
    fTextOutput.setEditable (false);

    // The grid fills the 3 columns sequentially.
    content_pane.add (buttons_panel);
    content_pane.add (fInputsPanel);
    content_pane.add (fTextOutput);

  } // init

  /** Handle the button events.**/
  public void actionPerformed (ActionEvent ae) {

    String str1 = fInputsPanel.fTextfieldTop.getText ();
    String str2 = fInputsPanel.fTextfieldBot.getText ();

    double val1=0.0;
    double val2=0.0;

    try {
      val1 = Double.parseDouble (str1);
      val2 = Double.parseDouble (str2);
    } catch  (NumberFormatException nfe){
      System.out.println ("Improper input");
    }

    if (ae.getActionCommand ().equals ("Add") ){
        fTextOutput.setText ("x + y = " +  (val1+val2));
    } else {
        fTextOutput.setText ("x * y = " +  (val1*val2));
    }
  } // actionPerformed

} // class MultiPanelWithEvents

 

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

/** JPanel subclass with two buttons. **/
public class ActionButtonsPanel extends JPanel {

  /** Constructor adds 2 buttons to the panel and
    * adds the listener passed as an argument.
   **/
  ActionButtonsPanel (ActionListener listener) {

    // Create two buttons
    JButton add_but =  new JButton ("Add" );
    JButton mult_but = new JButton ("Mult");

    add_but.addActionListener (listener);
    mult_but.addActionListener (listener);

    // Put a button in each grid cell
    add (add_but);
    add (mult_but);
  } // ctor
  
} // class ActionButtonsPanel

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

/** Panel to hold input textfields. **/
public class InputsPanel extends JPanel {

  JTextField fTextfieldTop=null;
  JTextField fTextfieldBot=null;

  /** Constructor builds panel with labels and text fields. **/
  InputsPanel (String label_str_top, String init_top,
               String label_str_bot, String init_bot) {

    // Set the layout with 2 rows by 2 columns
    setLayout (new GridLayout (2,2));

    // Create two text fields with the initial values
    fTextfieldTop = new JTextField (init_top);
    fTextfieldBot = new JTextField (init_bot);

    // Create the first label and right justify the text
    JLabel label_top =
     
new JLabel (label_str_top, SwingConstants.RIGHT);

    // Insert the label and textfield into the top grid row
    add (label_top);
    add (fTextfieldTop);

    // Create the second label and right justify the text
    JLabel label_bot =
      new JLabel (label_str_bot, SwingConstants.RIGHT);

    // Insert the second label and textfield into the bottom grid row
    add (label_bot);
    add (fTextfieldBot);
  } // ctor

} // class InputsPanel

 

Latest update: March 8, 2006

           Tech
Histogram UI
  Demo 1
Probablity Distrib.
  Demo 2 Demo 3
RejectionMethod
Histogram Stats
  Demo 4
Exercises

           Physics
Sim & Randomness
Custom Prob. Dist.
   Demo 1
Histogram Dist.
   Demo 2
Monte Carlo
  Demo 3
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.