Java Swing Tutorials - Herong's Tutorial Examples - v4.32, by Herong Yang
AWT Button Action Handler at the Component Level
This section provides a tutorial example on how to create an AWT 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 Button class to implement the ActionListener class:
/* ButtonAction.java * Copyright (c) 1997-2024 HerongYang.com. All Rights Reserved. */ import java.awt.Frame; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ButtonAction1 { public static void main(String[] a) { Frame f = new Frame("My AWT Button"); Button b = new MyButton(); f.add(b); f.pack(); f.setVisible(true); } private static class MyButton extends Button implements ActionListener { String text = "On"; public MyButton() { super(); setLabel(text); addActionListener(this); } public void actionPerformed(ActionEvent e) { if (text.equals("On")) text = "Off"; else text = "On"; setLabel(text); } } }
If you run this example, you will get:
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
Introduction of Java Swing Package
Graphics Environment of the Local System
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
JEditorPane - The Editor Pane Class
SwingWorker - The Background Task Worker
►AWT (Abstract Windows Toolkit)
What Is AWT (Abstract Windows Toolkit)
HelloAWT.java - My First AWT Program
Closing AWT Frame and Terminating Application
Drawing Graphics - Using paint() on Frame or Component
Creating Labels with java.awt.Label Class
Creating Buttons with java.awt.Button Class
►AWT Button Action Handler at the Component Level
AWT Button Action Handler at the Frame Level
AWT Button Mouse Click Handler at the Frame Level
AWT TextField and ActionListener
MenuBarTest.java - AWT Menu Bar Test Program
MenuTest.java - AWT Menu Test Program
MenuItemTest.java - AWT Menu Item Test Program
MenuItemActionListenerTest.java - AWT Menu Item Action Listener