Way2Java

Java AWT Button Learn GUI 8 Steps

The java.awt package comes with many GUI components of which Button is the most important and most frequently used. A button functionality (what for it is) can be known by its label like OK or Cancel etc. A mouse click on the button generates an action.

Following is the class signature

public class Button extends Component implements Accessible

Any GUI component with event handling can be broadly divided into 8 steps.

  1. Import java.awt and java.awt.event packages
  2. Extending frame or applet and implementing appropriate listener interface that can handle the events of the component successfully.
  3. Set the layout.
  4. Create components
  5. Register or link the component with the listener interface
  6. Beautification of the components (optional)
  7. Adding the components to the frame or applet
  8. Override all the abstract methods of the listener interface

By using the above 8 steps, let us develop a simple button program with 4 buttons with labels RED, GREEN, BLUE and CLOSE. The action is, the background of the frame should change as per the button clicked. When CLOSE is clicked, the frame should close.

Example code on Java AWT Button Learn GUI 8 Steps
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo1 extends Frame implements ActionListener
{
  Button redBut, greenBut, blueBut, closeBut;
  public ButtonDemo1()
  {
    setLayout(new FlowLayout());

    redBut = new Button("RED");
    greenBut = new Button("GREEN");
    blueBut = new Button("BLUE");
    closeBut = new Button("CLOSE");

    redBut.addActionListener(this);
    greenBut.addActionListener(this);
    blueBut.addActionListener(this);
    closeBut.addActionListener(this);
     
    closeBut.setForeground(Color.red);

    add(redBut);
    add(greenBut);
    add(blueBut);
    add(closeBut);

    setTitle("Buttons in Action");
    setSize(300, 300);
    setVisible(true);
  }
  public void actionPerformed(ActionEvent e)
  {
    String str = e.getActionCommand();

    if(str.equals("RED"))
      setBackground(Color.red);
    else if(str.equals("GREEN"))
      setBackground(Color.green);
    else if(str.equals("BLUE"))
      setBackground(Color.blue);
    else if(str.equals("CLOSE"))
      System.exit(0);
   }
   public static void main(String args[])
  {
    new ButtonDemo1();
  }
}


Step-By-Step Analysis of Java AWT Button Learn GUI 8 Steps

This being the first program you are learning on GUI application development, let us explain step-by-step process very clearly used in the above 8 steps.

1st step – Import java.awt and java.awt.event packages

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

The above two packages are very much required for every GUI application requiring event handling. The classes like Frame, Button and Color etc. used in the above program belong to java.awt package. ActionListener interface and ActionEvent class used belong to java.awt.event package.

2nd step – Extending frame or applet and implementing listener interface

public class ButtonDemo1 extends Frame implements ActionListener

The two frequently used top-level windows in AWT are Frame and Applet. After extending the required container like Frame, the next job is choosing an appropriate listener interface that can handle the events of the component very successfully. Here, the component is Button and the events of the button are handled by ActionListener.

3rd step – Set the layout

The third step is choosing the required layout for laying the components. Choose such a layout that gives always user-friendly environment to the user. For example, keeping a OK button on the right-side top corner would not like nice. We have chosen here FlowLayout.

setLayout(new FlowLayout());

For more clarity, the above statement can be divided into two.

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

A FlowLayout object is created and passed to setLayout() method. The setLayout() method sets the specified layout to the frame. All the components added are added under the influence of FlowLayout.

4th step – Create components

redBut = new Button("RED");
greenBut = new Button("GREEN");
blueBut = new Button("BLUE");
closeBut = new Button("CLOSE");

Four reference variables of Button are declared before constructor. In the above statements, the four reference variables are converted into objects. The Button constructor takes a string as parameter and this string becomes the label when the button is displayed.

5th step – Register the component with the listener interface

The buttons redBut, greenBut etc. created are no way connected or linked to the ActionListener. The following statements link or register the buttons with the listener; else ActionListener does not know whose buttons' action it should handle.

redBut.addActionListener(this);
greenBut.addActionListener(this);
blueBut.addActionListener(this);
closeBut.addActionListener(this);

addActionListener() is a method of Button class and the parameter "this" refers to the ActionListener. In this way, Button redBut etc. are registered with the ActionListener interface. When registered, it is the ActionListener responsibility to handle the events raised by the buttons. Generally a novice forgets this step and gets puzzled to debug as program compiles and runs nice but without any actions when the buttons clicked.


6th step – Beautification of the components

closeBut.setForeground(Color.red);

CLOSE button should be taken extra care as by mistake clicked, the whole application exits. For this reason the button is given a foreground color of red.

7th step – Adding the components to the frame or applet

After the creation, linking to the listener and beautification, finally the components are to be added to the container like frame. Without adding to a container like frame or applet, the buttons can not be made to appear (visualized) to the user.

add(redBut); add(greenBut); add(blueBut); add(closeBut);

8th step – Override all the abstract methods of the listener interface

This is a very important step where the actual code for the event is to be included. We know when an interface is implemented, all its abstract methods are to be overridden. For our luckiness, the ActionListener includes only one abstract method – actionPerformed() (remember, WindowListener includes 7 abstract methods). In the program, the actionPerformed(ActionEvent) method is overridden.

String str = e.getActionCommand();

The getActionCommand() method of ActionEvent class returns the label of the button clicked by the user as a string. This string str is used to differentiate the button clicked and as per the str, an appropriate action is taken. In the code, the background of the frame is changed.

System.exist(0);

This statement closes the frame (other way, the whole application exits) with exit() method of System class. 0 indicates normal shutdown.

setBackground(Color clr) and setForeground(Color clr) are the methods java.awt.Component class inherited by all the containers and components. setBackground() method sets the background color and setForeground() sets the foreground color to the component.