Panel in Java AWT


The class Panel is the simplest container class. It provides space in which an application can attach any other component, including other panels. It uses FlowLayout as default layout manager.

This code creates a simple AWT (Abstract Window Toolkit) application in Java. It defines a class MyApp that extends Frame and creates a window with a title "Tutor Joes" and a size of 1000x600 pixels. It sets the layout to null and makes the window visible.

In the MyApp constructor, a Panel is created with a gray background color and added to the window using the add method. Two Button components are added to the panel, each with a different background color.

The windowClosing method is also implemented using a WindowAdapter to handle the event when the user closes the window. It simply calls System.exit(0) to terminate the program. The main method creates an instance of MyApp and starts the application.

Source Code

package awtDemo;
 
import java.awt.*;
import java.awt.event.*;
 
//Panel in AWT
class MyApp extends Frame {
 
	public MyApp() {
		super("Tutor Joes");
		setSize(1000, 600);// w,h
		setLayout(null);
		setVisible(true);
 
 
		    Panel panel=new Panel();  
	        panel.setBounds(40,80,200,200);    
	        panel.setBackground(Color.gray);
 
	        Button b1=new Button("Button 1");     
	        b1.setBounds(50,100,80,30);   
	        b1.setBackground(Color.yellow); 
 
	        Button b2=new Button("Button 2");   
	        b2.setBounds(100,100,80,30);    
	        b2.setBackground(Color.green);
 
	        panel.add(b1); 
	        panel.add(b2);  
 
	        add(panel);  
 
		// Close Button Code
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				System.exit(0);
			}
		});
	}
 
}
 
public class app {
	public static void main(String[] args) {
		MyApp frm = new MyApp();
	}
 
}
 
To download raw file Click Here

Output

Java AWT


Basic Programs