The JButton Class

JButton is the simplest of the button types, adding very little to what is provided by the AbstractButton class. JButtons are buttons that are not toggled on and off but instead act as push buttons, which invoke some action when clicked.

Using the Default Button

import javax.swing.*;
import java.awt.*;

// Example using defaultButton and JRootPane.setDefaultButton( )
public class DefaultButtonExample {
	public static void main(String[] args) {

		// Create some buttons.
		JButton ok = new JButton("OK");
		JButton cancel = new JButton("Cancel");
		JPanel buttonPanel = new JPanel();

		JLabel msg = new JLabel("Is this OK?", JLabel.CENTER);

		// Create a frame, get its root pane, and set the OK button as the
		// default. This
		// button is pressed if we press the Enter key while the frame has
		// focus.
		JFrame f = new JFrame();
		JRootPane root = f.getRootPane();

		// Layout and display
		Container content = f.getContentPane();
		content.add(msg, BorderLayout.CENTER);
		content.add(buttonPanel, BorderLayout.SOUTH);
		f.setSize(200, 100);