Java Swing Tutorials - Herong's Tutorial Examples - v4.32, by Herong Yang
Creating Buttons with javax.swing.JButton Class
This section provides a tutorial example on how to create a button with the javax.swing.JButton class.
Buttons are so easy to create with the javax.swing.JButton class. Here is a sample program:
/* JButtonOk.java * Copyright (c) 1997-2024 HerongYang.com. All Rights Reserved. */ import java.awt.*; import javax.swing.*; public class JButtonOk { public static void main(String[] a) { JFrame f = new JFrame("My First Button"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton b = new JButton("OK"); f.getContentPane().add(b); f.pack(); f.setVisible(true); } }
If you run this example, you will get:
Note: Clicking the OK button will trigger no actions, because no event listeners are added to the button component.
Table of Contents
Introduction of Java Swing Package
Graphics Environment of the Local System
►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
JEditorPane - The Editor Pane Class
SwingWorker - The Background Task Worker
AWT (Abstract Windows Toolkit)