How to Create Push Buttons with JButton

Button is one of the simplest UI components, that is used to generate events when 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 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.

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 are “OK” and “Cancel”.
  • To add event handler for 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.