Java Swing Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.00

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) 2002 by Dr. Herong Yang, http://www.herongyang.com/
 */
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:
JButton Text Button

Note: Clicking the OK button will trigger no actions, because no event listeners are added to the button component.

Sample programs listed in this section have been tested with JDK 1.3.1, 1.4.1, 1.5.0, and 1.6.0.

Last update: 2009.

Sections in This Chapter

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

Dr. Herong Yang, updated in 2009
Creating Buttons with javax.swing.JButton Class