Java JButton Tutorial with ActionListener Programming Examples

In this tutorial you will learn:

1. How to use JButton in Swing Application?
2. How to use ActionListener in JButton?
3. How to track Button click?

Java JButton in Swing

Java JButton in swing is used for performing action when clicked on it. This action might be getting data from input field, saving or retrieving data to database or performing and displaying calculation result in swing frame. Following classes and methods are used for implementing JButton in Swing.

Constructors

ConstructorDescription
JButton()It creates a button with no text and icon.
JButton(String s)It creates a button with the specified text.
JButton(Icon i)It creates a button with the specified icon object.

Methods

MethodsDescription
void setText(String s)It is used to set specified text on button
String getText()It is used to return the text of the button.
void setEnabled(boolean b)It is used to enable or disable the button.
void setIcon(Icon b)It is used to set the specified Icon on the button.
Icon getIcon()It is used to get the Icon of the button.
void setMnemonic(int a)It is used to set the mnemonic on the button.
void addActionListener (ActionListener a)It is used to add the action listener to this object.

Programming Example

Output:
output

Action Listener

This was the simple JButton example that performed nothing when clicking on it. Now, I will add action listener so, this button will perform some action on clicking.

Example 1: Simple Button Action Listener Program

Output

Example 2: Call a Method in Action Listener

Output

Example 3: Track Which Button is Clicked and Display Message

Output

Summary

In this tutorial you learn how to play with JButton in Swing Application. I have tried to explain JButton with suitable, easy and complete programming example. In the next chapter you will learn some inputs field of Swing like JTextField, JPasswordField, JTextArea and JLabel


Leave a Reply

Your email address will not be published. Required fields are marked *