Button Action Handler at the Component Level

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

One way to handle button actions is to add an action listener to the button object. An action listener is an object of any class that implements the ActionListener interface.

The following program shows you how to extend the JButton class to implement the ActionListener class:

/* JButtonAction1.java
 * Copyright (c) 1997-2024 HerongYang.com. All Rights Reserved.
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonAction1 {
   public static void main(String[] a) {
      JFrame f = new JFrame("My Switch Button");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JButton b = new MyButton();
      f.getContentPane().add(b);
      f.pack();
      f.setVisible(true);
   }
   private static class MyButton extends JButton 
      implements ActionListener {
       String text = "On";
       public MyButton() {
          super();
          setText(text);
          addActionListener(this);
       }
       public void actionPerformed(ActionEvent e) {
          if (text.equals("On")) text = "Off";
          else text = "On"; 
          setText(text);
       }
   }
}

If you run this example, you will get:

JButton Button Action Handler at Component
JButton Button Action Handler at Component

The button works well. If you click the button, the button label text will change from "On" to "Off"; and from "Off" to "On", if you click it again.

Table of Contents

 About This Book

 JDK (Java Development Kit)

 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

 JCheckBox - Swing Check Box Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 JComboBox - Swing Combo Box 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

 AWT (Abstract Windows Toolkit)

 Integration with Desktop System

 Archived Tutorials

 References

 Full Version in PDF/EPUB