Swing JButton

In this tutorial you will learn about the Swing JButton and its application with practical example.

Swing JButton

The Jbutton which is implementation of push button is used to create labelled button. On pressing it generate an event. The JButton inherits AbstractButton and implements Accessible.

Declaration of JButton class

JButton Constructor

Some of commonly used constructor are listed below.

JButton()

This constructor is used to creates a button with no set text and icon.

Syntax:-

JButton(String text)

This constructor is used to creates a button with text.

Syntax:-

JButton(Icon i)

If you want to set an Icon on your button so this constructor is used.

Syntax:-

JButton(String text, Icon i)

This constructor is used to creates a button with initial text and an icon.

Syntax:-

JButton(Action a)

This constructor is used to creates a button where properties are taken from the action supplied.

Syntax:-

Swing JButton Methods

Some of commonly used methods are listed below.

void setText(String text): This method is used to set Text on Button.

String getText(): This method is used to get Text of Button and return type is String.

void setEnabled(boolean b): This method is used to Enable and disable the Button.

void setIcon(Icon ic): This method is used to set icon on Button.

Icon getIcon(): This method is used to get Icon of Button.

void setMnemonic(int i): This method is used to set Mnemonic on the JButton.

AccessibleContext getAccessibleContext(): This method is used to get the AccessibleContext which is associated with JButton.

String getUIClassID(): This method specifies the name of the L&F class that renders this component and returns a String.

boolean isDefaultButton(): This method is used to get defaultButton property and returns boolean.

boolean isDefaultCapable: This method is used to get the value of the defaultCapable property and returns boolean.

protected String paramString(): This method is used to returns a string representation of this JButton.

void updateUI(): This method is used to resets the UI property.

JButton Inherited Methods

This class inherits methods from the following class:

  1. javax.swing.AbstractionButton.
    2. javax.swing.JComponent.
    3. java.awt.Container.
    4. java.awt.Component.
    5. java.lang.Object.

Lets understand it by an example. First we need to create a class like below code:

The output of this code will look like below Image

image001

Example of JButton with ActionListener : Lets write code for ActionListener of JButton

The Output of above example will look like below image

image003

Example of JButton with Icon: Lets do coding for displaying icon on button

Output of this code will look like below image

image005

In this tutorial we have learn about the Swing JButton and its application with practical example. I hope you will like this tutorial.