JAVA Swing Button Example

In this article we will learn different types of Button and how to create them. A button is a component that a user clicks to trigger a specific action.To add a cross platform button JButton class is used.

The abstract class AbstractButton extends class JComponent .To create a button, you can instantiate one of the many classes that descend from the AbstractButton class.

1. Introduction

There are different types of buttons in Java and are subclasses of AbstractButton .

  • Common Button: is created using class JButton. Event generated by this button is ActionEvent.
  • Check Box: Group of buttons, generating event type of ItemEvent
  • Radio Button: Group of buttons out of which allows only one button to be selected. It generates ItemEvent.
  • Toggle Button: Toggles between on/off or true/false values.

2 JAVA Swing Button

2.1 Class declaration of Button

Following is the declaration for javax.swing.JButton class −

class declaration

public class JButton
   extends AbstractButton
      implements Accessible

2.2 The Button API

Common used API for JButtonare discussed below:

2.2.1 Setting or Getting the Button’s Contents.

Constructors to create instance of Button are described below.

  • JButton() Creates a button with no set text or icon.
  • JButton(Action) Creates a button where properties are taken from the Action supplied.
  • JButton(String, Icon) Creates a button with initial text and an icon.
  • JButton(String) Creates a button with text.
  • JButton(Icon) Creates a button with an icon.

Some of the commonly used methods of Button class are described below

  • void setAction(Action), Action getAction() Set or get the button’s properties according to values from the Action instance.
  • void setText(String),String getText() Set or get the text displayed by the button.
  • void setIcon(Icon),Icon getIcon() Set or get the image displayed by the button when the button isn’t selected or pressed.
  • void setPressedIcon(Icon),Icon getPressedIcon() Set or get the image displayed by the button when it is being pressed.

2.2.2 Fine Tuning the Button’s Appearance.

Some of the commonly used methods uder this API are described below:

  • void setHorizontalAlignment(int),void setVerticalAlignment(int),int getHorizontalAlignment(),int getVerticalAlignment() Set or get where in the button its contents should be placed. The AbstractButton class allows any one of the following values for horizontal alignment: RIGHT, LEFT, CENTER (the default), LEADING, and TRAILING. For vertical alignment: TOP, CENTER (the default), and BOTTOM.
  • void setHorizontalTextPosition(int),void setVerticalTextPosition(int),int getHorizontalTextPosition(),int getVerticalTextPosition() Set or get where the button’s text should be placed, relative to the button’s image. The AbstractButton class allows any one of the following values for horizontal position: LEFT, CENTER, RIGHT, LEADING, and TRAILING (the default). For vertical position: TOP, CENTER (the default), and BOTTOM.

2.2.3 Implementing the Button’s Functionality.

Some of the commonly used methods uder this API are described below:

  • void setMnemonic(int),char getMnemonic() Set or get the keyboard alternative to clicking the button. One form of the setMnemonic method accepts a character argument; however, the Swing team recommends that you use an int argument instead, specifying a KeyEvent.VK_X constant.
  • void setActionCommand(String),String getActionCommand() Set or get the name of the action performed by the button.
  • void addActionListener(ActionListener),ActionListener removeActionListener() Add or remove an object that listens for action events fired by the button.
  • void addItemListener(ItemListener),ItemListener removeItemListener() Add or remove an object that listens for item events fired by the button.
  • void setSelected(boolean),boolean isSelected() Set or get whether the button is selected. Makes sense only for buttons that have on/off state, such as check boxes.

2.3. Setup

This Example demonstrates how to create a Button using Swing in eclipse.

This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work. To learn how to install WindowBuilder tool please visit the Setup section 2.1 of the following link click here.

Create a new JAVA project lets say swing_1

    • Go to src→ right click→ New→ Other→ WindowBuilder→ select Swing Designer→ Application Window
    • Enter the name of the application(eg. SwingButtonExample ) and click finish.

This will create SwingButtonExample.java file and will provide Source and Design tab.

3. Code

A Swing button can display both text and an image. The underlined letter in each button’s text shows the mnemonic — the keyboard alternative — for each button. In most look and feels, the user can click a button by pressing the Alt key and the mnemonic. For example, Alt-M would click the Middle button in SwingButtonExample.

Button’s disabled appearance automatically generates to the look and feel of a button when a button is disabled.
Implementation of event handling depends on the type of button used and how it has been used.

Mostly, an action listener is implemented which gets notification when an event is generated by user such as, mouse click or Hovering of mouse over button etc. When the check box is selected or deselected it generates an event which notifies to item listener.

Here is the code explained for java swing button. In this example we have created 3 buttons, i.e, enable, disable and middle button. enable button when clicked enables 2 button, i.e, middle and disable where as, disable button when clicked disables 2 button enable and middle and enables enable button. middle button when clicked display message that middle button has been clicked.


package swing_1;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class SwingButtonExample extends JPanel
                        implements ActionListener {
    protected JButton b1, b2, b3;
    public SwingButtonExample() {
        b1 = new JButton("Disable middle button");
        b2 = new JButton("Middle button");
        b3 = new JButton("Enable middle button");
        //Use the default text position of CENTER, TRAILING (RIGHT).

In the above code 3 buttons, i.e, b1, b2 and b3 is created . Properties related to each button is set. setVerticalTextPosition() Sets the vertical position of the text relative to the icon. setHorizontalTextPosition() Sets the horizontal position of the text relative to the icon. setActionCommand Sets the action command for the relative button. setMnemonic Sets the keyboard mnemonic on the current model.

The mnemonic is the key which when combined with the look and feel’s mouseless modifier (usually Alt) will activate this button if focus is contained somewhere within this button’s ancestor window.


        b1.setToolTipText("Click this button to disable the middle button.");
        b2.setToolTipText("This middle button prints something when you click it.");
        b3.setToolTipText("Click this button to enable the middle button.");
        //Add Components to this container, using the default FlowLayout.

Here in the above code we add action listeners on each of the button. setToolTipText Registers the text to display in a tool tip. The text displays when the cursor lingers over the component. Buttons are added to the container using add(component).


 public void actionPerformed(ActionEvent e) {
        if ("disable".equals(e.getActionCommand())) {
        } else if("middle".equals(e.getActionCommand()))
        	JOptionPane.showMessageDialog(this.getComponent(0), "Middle button is clicked");
        else {

In the above code when an event is generated, i.e, clicking of mouse it generates an event and an action is performed based on the implementation of action performed method.


    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SwingButtonExample");
        //Create and set up the content pane.
        SwingButtonExample newContentPane = new SwingButtonExample();
        newContentPane.setOpaque(true); //content panes must be opaque
        //Display the window.
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {

The above code describes how to create a GUI, i.e, creation of frame and adding a content pane to it.

After Execution of code Swing Button will look like this:

JAVA Swing Button Example
JAVA Swing Button Example

4. Download

This was an example of creation of JAVA Swing Button.

You can download the full source code of this example here: SwingButtonExample

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Jyoti Jha

Jyoti is a tech enthusiast and is an avid programmer. She holds a post graduation degree in (M.Tech) Computer Science Engineering from Thapar Univeristy, Patiala, India. Post her graduate studies, she has worked in Software companies such as SLK Software and Aricent, India as Software Engineer in various projects primarily in the field of Requirement analysis and design, implementing new algorithms in C++ and JAVA used in ISDN network and designing databases and. She is inquisitive about socio economic reforms as well as advancement in technical fronts and keep herself informed with TED talks and various blogs.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button