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
Any GUI component with event handling can be broadly divided into 8 steps.
- Import java.awt and java.awt.event packages
- Extending frame or applet and implementing appropriate listener interface that can handle the events of the component successfully.
- Set the layout.
- Create components
- Register or link the component with the listener interface
- Beautification of the components (optional)
- Adding the components to the frame or applet
- 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();
}
}

without implementing ActionListener can we write like this
redBut.addActionListener(new Button.ActionListener);
How new Button and redButt are linked.
is there any other way that links btn to Listener?
Hi sir i program explanation is very god thatks for this explanation sir,
Cani know how to execute this above program?
Open file by name ButtonDemo1.java, write the code in notepad and save, compile as javac ButtonDemo1 and execute as java ButtonDemo1
how we create labels,textbox and button
With Label component.