MenuBar,Menu,MenuItem in Java AWT


The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the MenuItem or any of its subclass.

This Java AWT code demonstrates how to create a Menu Bar using the AWT package in Java.

  • In the code, a class MyApp is created which extends the Frame class. The constructor of the class creates a MenuBar object m and sets it as the menu bar for the frame using the setMenuBar() method.
  • A Menu object menu and a SubMenu object submenu are created and added to the MenuBar object using the add() method. MenuItem objects i1, i2, i3, i4, and i5 are created and added to the Menu and SubMenu objects using the add() method.
  • Finally, the windowClosing() method is overridden to terminate the application when the window is closed.
  • When you run the above code, you will see a menu bar with a Menu and a SubMenu. The Menu has three items (Item 1, Item 2, Item 3) and the SubMenu has two items (Item 4, Item 5).

Source Code

package awtDemo;
 
import java.awt.*;
import java.awt.event.*;
 
//Menu Bar in AWT
 
class MyApp extends Frame {
 
 
 
	public MyApp() {
		super("Tutor Joes");
		setSize(1000, 600);// w,h
		setLayout(null);
		setVisible(true);
 
		     MenuBar m=new MenuBar();  
	         Menu menu=new Menu("Menu");  
	         Menu submenu=new Menu("Sub Menu");  
	         MenuItem i1=new MenuItem("Item 1");  
	         MenuItem i2=new MenuItem("Item 2");  
	         MenuItem i3=new MenuItem("Item 3");  
	         MenuItem i4=new MenuItem("Item 4");  
	         MenuItem i5=new MenuItem("Item 5");  
	         menu.add(i1);  
	         menu.add(i2);  
	         menu.add(i3);  
	         submenu.add(i4);  
	         submenu.add(i5);  
	         menu.add(submenu);  
	         m.add(menu);  
	         setMenuBar(m);  
 
 
 
		// 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