Java Button Example with ActionListener Event Handling

Java Button Example with ActionListener Event Handling

A simple Java Button Example given to understand how to create components and link to event handling mechanism.

User interface (communication-point) with a running Java program can be in two ways – using keyboard input and the other with GUI. Java supports GUI environment through GUI components like button, check box, radio button and menu etc. To support the GUI classes, Java comes with two packages – java.awt and javax.swing.

The most used GUI component is button. Button is used to accept something (like OK button) or reject something (like Cancel button). The button in java.awt package is represented by Button class. Like any other Java class, a Java Button can be instantiated and using the constructors and methods its properties, like background, foreground and label, can be changed.

Following is a simple program where three Java button objects with labels Red, Green and Blue are created and added to frame to display. Depending on the button clicked, the background color of the frame is changed.

Java Button

Let us explain the code.

FlowLayout fl = new FlowLayout();

A layout is set to the frame with FlowLayout. The above two statements can be repalced with one as follows.

setLayout(new FlowLayout());

rb = new Button(“Red”)

A Java button object rb is created and linked with the ActionListener. The parameter "this" represents ActionListener. If linking is not done, program displays three buttons but without event handling

String str = e.getActionCommand();

getActionCommand() method of ActionEvent class returns the label of the button clicked by the user as a string. str represents the label of the button. Using str, the programmer can do some action.


str becomes equal to Red when the user clicked Red button. Now change the background of the frame with red color with method setBackground().

Lot of explanation is available on this program at Java AWT Button – Learning GUI – 8 Steps

One thought on “Java Button Example with ActionListener Event Handling

Leave a Reply

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