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
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
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.
For more clarity, the above statement can be divided into two.
FlowLayout fl = new FlowLayout();
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.
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.