swing

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.

Prerequisite
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.

SwingButtonExample.java

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");
        b1.setVerticalTextPosition(AbstractButton.CENTER);
        b1.setHorizontalTextPosition(AbstractButton.LEADING); 
        b1.setMnemonic(KeyEvent.VK_D);
        b1.setActionCommand("disable");
 
        b2 = new JButton("Middle button");
        b2.setVerticalTextPosition(AbstractButton.BOTTOM);
        b2.setHorizontalTextPosition(AbstractButton.CENTER);
        b2.setActionCommand("middle");
        b2.setMnemonic(KeyEvent.VK_M);
 
       
        b3 = new JButton("Enable middle button");
        //Use the default text position of CENTER, TRAILING (RIGHT).
        b3.setMnemonic(KeyEvent.VK_E);
        b3.setActionCommand("enable");
        b3.setEnabled(false);

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.

SwingButtonExample.java

        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
 
        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.
        add(b1);
        add(b2);
        add(b3);

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).

SwingButtonExample.java

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

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.

SwingButtonExample.java

    private static void createAndShowGUI() {
 
        //Create and set up the window.
        JFrame frame = new JFrame("SwingButtonExample");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Create and set up the content pane.
        SwingButtonExample newContentPane = new SwingButtonExample();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
 
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
 
    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() {
                createAndShowGUI(); 
            }
        });
    }
}

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.

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

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.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button