Button and ActionListener in Java AWT


The Java ActionListener is notified whenever you click on the button or menu item. It is notified against ActionEvent.

An ActionListener can be used by the implements keyword to the class definition. It can also be used separately from the class by creating a new class that implements it. It should also be imported to your project.

This is another Java program that uses AWT to create a GUI. This program creates a separate MyApp class that extends the Frame class to create a window with the title "Tutor Joes". The setLayout(null) method sets the layout of the window to null, which means that the components added to the window will be manually positioned using absolute coordinates.

The program creates a button labeled "Click Me" using the Button class, sets its position and size using the setBounds() method, and adds it to the window using the add() method.

The setSize(1000,600) method sets the size of the window to 1000x600 pixels, and setVisible(true) makes the window visible on the screen. The main() method creates an instance of the MyApp class and shows the window on the screen.

This program is similar to the previous one, but it creates a separate class to create the window. This approach is better for larger programs because it allows for better organization and separation of concerns.

Source Code

package awtDemo;
import java.awt.*;
class MyApp extends Frame
{
	Button btn;
 
	public MyApp()
	{
		super("Tutor Joes");
		setLayout(null);
 
		btn=new Button("Click Me");
		btn.setBounds(75,75,200,50);
		add(btn);
		setSize(1000,600);
		setVisible(true);
 
	}
 
}
 
 
public class app
{
	public static void main(String args[])
	{
		MyApp frm =new MyApp();
	}
To download raw file Click Here

Output

Java AWT


Basic Programs