Java AWT Menu Class
The Java AWT Menu class represents a pop-up menu component in a graphical user interface (GUI) that can contain a collection of MenuItem objects. It provides a way to create and manage menus in Java AWT applications.
Syntax of Class Declaration of Menu
public class Menu extends MenuItem
Methods of the Menu Class
List of methods available in MenuItem with description
Method |
Description |
---|---|
public Menu(String label) |
Constructs a new menu with the specified label. |
public void add(MenuItem mi) |
Adds the specified menu item to the menu. |
public void addSeparator() |
Adds a separator between menu items within the menu. |
public MenuShortcut getShortcut() |
Returns the menu shortcut key associated with this menu. |
Example usage of the MenuItem & Menu
Java
//Java class to implement AWT Menu // and MenuItem import java.awt.*; import java.awt.event.*; //Driver Class public class MenuExample { //Main Method public static void main(String[] args) { Frame frame = new Frame( "Menu Example" ); MenuBar menuBar = new MenuBar(); frame.setMenuBar(menuBar); // Create a "File" menu Menu fileMenu = new Menu( "File" ); MenuItem openItem = new MenuItem( "Open" ); MenuItem saveItem = new MenuItem( "Save" ); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.addSeparator(); // Create an "Exit" menu item with an action listener MenuItem exitItem = new MenuItem( "Exit" ); exitItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit( 0 ); } }); //Added exit as item in MenuItem fileMenu.add(exitItem); menuBar.add(fileMenu); frame.setSize( 300 , 300 ); frame.setVisible( true ); } } |
This code creates a simple window with a “File” menu that contains “Open,” “Save,” and “Exit” options. When you click “Exit,” the application exits.
Output:
Output of the Example:
Java AWT MenuItem & Menu
Java Abstract Window Toolkit (AWT) provides a comprehensive set of classes and methods to create graphical user interfaces. In this article, we will explore the MenuItem and Menu classes, which are essential for building menus in Java applications.