How to Create Push Buttons with JButton

Button is one of the simplest UI components, that is used to generate events when the user clicks or presses on it. Swing button can display text, icon or both.

The state of Swing button is maintained by a ButtonModel object. The ButtonModel interface defines methods for reading and writing model’s properties or adding and removing event listeners.

There is an implementation of the ButtonModel interface called DefaultButtonModel. The DefaultButtonModel is used directly by AbstractButton class. The AbstractButton is the base class for all Swing button components (JButton, JToggleButton, JCheckbox, JRadioButton, and JMenuItem).

In this tutorial, we will show you how to use JButton class to create simple buttons and add event handlers to them.

Here is the source code of JButton demo application.

package jbuttondemo1; 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 Main { public static void main(String[] args) { final JFrame frame = new JFrame(); // Create OK button JButton btnOK = new JButton("OK"); // Add event handler for OK button btnOK.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(frame, "You've clicked OK button" ); } }); // Create Cancel button JButton btnCancel = new JButton("Cancel"); btnCancel.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(frame, "You've clicked Cancel button" ); } }); // Add buttons to a panel JPanel buttonPanel = new JPanel( ); buttonPanel.add(btnOK); buttonPanel.add(btnCancel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.getContentPane( ).add(buttonPanel,BorderLayout.SOUTH); frame.setVisible(true); } }
Code language: JavaScript (javascript)

In the application, above we’ve done the following steps:

  • Create a new instance of JButton class. In this case, we create a new button and passing the text to display on that button which is “OK” and “Cancel”.
  • To add an event handler for the button, use the method addActionListener. You see we create an anonymous class as a parameter of the method. We put our code to handle event inside the method actionPerformed. In this case, we show a message dialog to notify that user has clicked the corresponding button.
  • Then we add buttons to a panel and add this panel to the frame.