Button Action Handler at the Frame Level

This section provides a tutorial example on how to create a button to handle actions by adding the ActionListener interface to the frame that contains the button component.

In the previous section, we extended the button to handle its own action. That works fine, if the action only requires modifying the behavior of the same button.

But if the action requires modifying the behavior of other components, you need to implement the action listener as a higher level. The following program shows you how to use the action handler to modify the text of a label component:

/* JButtonAction2.java
 * Copyright (c) 2014, HerongYang.com, All Rights Reserved.
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonAction2 implements ActionListener {
   JButton myButton = null;
   JLabel myLebal = null;
   String text = null;
   public static void main(String[] a) {
      JButtonAction2 myTest = new JButtonAction2();
      myTest.createFrame();
   }
   public void createFrame() {
      JFrame f = new JFrame("My Switch Button");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();
      c.setLayout(new GridLayout(2,1));
      text = "On";
      myButton = new JButton(text);
      myButton.addActionListener(this);
      c.add(myButton);
      myLebal = new JLabel(text,SwingConstants.CENTER);
      c.add(myLebal);
      f.pack();
      f.setVisible(true);
   }
   public void actionPerformed(ActionEvent e) {
      if (text.equals("On")) text = "Off";
      else text = "On"; 
      myButton.setText(text);
      myLebal.setText(text);
   }
}

If you run this example, you will get:
JButton Button Action Handler

The button works nicely. If you click the button, the button label text will change from "On" to "Off", and the text of the label component will also change.

Sample programs listed in this section have been tested with JDK 1.3.1 to 1.8.0.

Last update: 2014.

Table of Contents

 About This Book

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

JButton - Swing Button Class

 Creating Buttons with javax.swing.JButton Class

 Creating Image Buttons with javax.swing.JButton Class

 Button Action Handler at the Component Level

Button Action Handler at the Frame Level

 Mouse Click Handler at the Frame Level

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 References

 PDF Printing Version