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.

import java.awt.*;
import java.awt.event.*;

public class ButtonDemo extends Frame implements ActionListener
{
  Button rb, gb, bb;		            // three Button reference variables
  public ButtonDemo()	                    // constructor to set the properties to a button
  {
    FlowLayout fl = new FlowLayout();	    // set the layout to frame
    setLayout(fl);

    rb = new Button("Red");		    // convert reference variables into objects
    gb = new Button("Green");
    bb = new Button("Blue");

    rb.addActionListener(this);		    // link the Java button with the ActionListener
    gb.addActionListener(this);
    bb.addActionListener(this);

    add(rb);			            // add each Java button to the frame
    add(gb);
    add(bb);   

    setTitle("Button in Action");
    setSize(300, 350);                      // frame size, width x height
    setVisible(true);			    // to make frame visible on monitor, default is setVisible(false)
  }
			                    // override the only abstract method of ActionListener interface
  public void actionPerformed(ActionEvent e)
  {
    String str = e.getActionCommand();	    // to know which Java button user clicked
    System.out.println("You clicked " + str + " button");  // just beginner's interest

    if(str.equals("Red"))
    {
      setBackground(Color.red);
    }
    else if(str.equals("Green"))
    {
      setBackground(Color.green);
    }
    else if(str.equals("Blue"))
    {
      setBackground(Color.blue);
    }
  }
  public static void main(String args[])
  {
    new ButtonDemo();                       // anonymous object of ButtonDemo just to call the constructor
  }			                    // as all the code is in the constructor
}

Java Button

Let us explain the code.

FlowLayout fl = new FlowLayout();
setLayout(fl);

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”)
rb.addActionListener(this);

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.

if(str.equals(“Red”))
{
setBackground(Color.red);
}

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

1 thought on “Java Button Example with ActionListener Event Handling”

Leave a Comment

Your email address will not be published.