JButton in Java Swing with Examples

JButton in Java is defined in javax.swing package .

JButton in child of javax.swing.AbstractButton.

public class JButton
extends AbstractButton
implements Accessible

To create instance of JButton many constructors are provided.

JButton Consturctor

Sr NoConstructors and Description
1JButton()
Creates a button with no set text or icon.
2JButton(Action a)
Creates a button where properties are taken from the Action supplied.
3JButton(Icon icon)
Creates a button with an icon.
4JButton(String text)
Creates a button with text.
5JButton(String text, Icon icon)
Creates a button with initial text and an icon.

Let us see all constructors one by one.

Commonly used AbstractButton methods

Sr NoMethod and Description
1String getText()
get the text of Button
2void setText​(String text)
Sets the button’s text.
3Icon getIcon()
Get the icon of Button
4void setIcon​(Icon defaultIcon)
Set the icon on button
5void addActionListener​(ActionListener l)
Add an action listener to a button
6void setEnabled​(boolean b)
Enable or disable the button based on boolean argument
7void setMnemonic​(int mnemonic)
Set the keyboard Mnemonic for button

Java JButton Examples

How to add Icon to JButton in Java

JButton in Java with constructor
Fig: JButton in Java with constructor

JButton Click and ActionListner Example

JButton Click and ActionListner Example
Fig: JButton Click and ActionListner Example

ActionCommand and Mnemonic Example in JButton

ActionCommand and Mnemonic Example in JButton
Fig: ActionCommand and Mnemonic Example in JButton

Image source https://freeicons.io/