Java AWT Button Learn GUI 8 Steps

Java AWT Button Learn GUI 8 Steps



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.

7 thoughts on “Java AWT Button Learn GUI 8 Steps

Leave a Reply

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