Site icon TestingDocs.com

Create a button with Swing JButton

Overview

In this tutorial, we will learn how to use the Swing JButton class to create simple buttons and add event handlers.

Swing JButton

Swing JButton class is the implementation of push-button. We can create a new instance of JButton class.

JButton btnOK = new JButton(“OK Button”);

In this case, we create a new push-button and pass the text to display on the button “OK Button”.

The button is the GUI component that generates events when the user clicks on it. The Swing button can display text, icon, or both. The state of the Swing button is maintained by a ButtonModel object.

The ButtonModel is an interface state model for buttons.
This model is used for regular buttons, as well as checkboxes
and radio buttons. It defines methods for reading and writing model’s properties or adding and removing events listeners.

Java Program

In the example program, we will add two push buttons to the panel and add the panel to the frame.

package com.testingdocs.swing.components;

/**********************************************
 * FileName: JButtonDemo.java
 * Package : com.testingdocs.swing.components
 * 
 * Java Tutorials - www.TestingDocs.com
 **********************************************/
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class JButtonDemo {
	public static void main(String[] args) {
		JFrame frame = new JFrame("JButtonDemo - www.TestingDocs.com");
		JButton btnOK = new JButton("OK Button"); // Create OK button
		// add event handler for OK button
		btnOK.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent e) {
						JOptionPane.showMessageDialog(frame,
								"OK button clicked."
								);
					}
				});

		JButton btnCancel = new JButton("Cancel Button");// create Cancel button
		btnCancel.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent e) {
						JOptionPane.showMessageDialog(frame,
								"Cancel button clicked."
								);
					}
				});

		// add buttons to the panel
		JPanel panel = new JPanel( );
		panel.add(btnOK);
		panel.add(btnCancel);
        
		//Frame properties
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(400, 300);
		frame.getContentPane( ).add(panel,BorderLayout.PAGE_END);
		frame.setVisible(true);
	}
}

Output

ActionListener is the listener interface for receiving action events. To add an event handler for the button, we can use the addActionListener() method.

Run the Java application to view the output.

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version