Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JButton and ActionListener

1. About JButton

In swing, we can create a push button using the JButton class. We can watch for the click event on it using the ActionListener. When the user clicks the button, it produces the ActionEvent, and the event will go to the registered Listener.

2. About the Example

The below screenshot shows the Example which we will create here:

JButton Example
JButton Example

It is a simple example which has only two components in it. One is JButton and the other one JLabel. When user clicks the Flip Mode button, the Label changes its caption from Read Mode to Write Mode. Upon clicking the button again, the label restores its original caption Read Mode. So during each click, the Label will alternate between the text Read Mode & Write Mode. Let us proceed with the coding:

3. Create JButton

The below code creates the Button and JLabel.

In line 7, we are creating the Jbutton. In the constructor, we passed a string which will appear as the button text. Next, we added this button to the JFrame Window. Note, the FlowLayout Manager manages the window. Also note the order in which we are adding the components. The same order the component flow occurs. Means Layout Manager will display the label before the button display.

4. Handle actionPerformed – Anonymous Inner Class

The Anonymous Inner class is the modern way of handling the Java Events. Here, in the below code, we create such a class for our JButton class. In this inner class, we handle provide the actionPerformed handler function. At line 38, we check the text of the current Label. Based on the outcome, we flip the label’s text. Note, when we use Anonymous Inner class for handling the component events, we no need to check the event originator. Because the inner class is a specific to the component.

5. Watch JButton Example as Youtube Video

Youtube: JButton Example

6. Code Reference

6.1 MainEntry.java

6.2 JButtonExample.java

Categories: Swing

Tags: , ,

Do you like this Example? Please comment about it for others!!

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