MENUS IN JAVA
A menu in Java is a graphical control element that provides a list of commands
or options that a user can select to perform specific actions in a GUI
application. Menus are created using classes from the [Link] package.
Purpose of Menus
To organize commands or options in a structured way
To make user interfaces easy and user-friendly
To allow quick access to actions like Open, Save, Exit, etc.
The main components are:
1. MenuBar
Represents the menu bar at the top of a window.
Syntax-
MenuBar menuBar = new MenuBar(); [Link](menuBar);
2. Menu
Represents a drop-down menu.
Syntax-
Menu fileMenu = new Menu("File");
[Link](fileMenu);
3. MenuItem
Represents a single clickable option in a menu.
Syntax-
MenuItem openItem = new MenuItem("Open");
[Link](openItem);
4. CheckboxMenuItem
A menu item with a checkbox.
Syntax-
CheckboxMenuItem showLogs = new CheckboxMenuItem("Show Logs");
[Link](showLogs);
Creating a Simple Menu Example
import [Link].*;
import [Link].*;
public class SimpleMenuExample {
public static void main(String[] args) {
Frame frame = new Frame("Simple Menu Example");
// Create a menu bar
MenuBar menuBar = new MenuBar();
// Create a menu
Menu fileMenu = new Menu("File");
// Create menu items
MenuItem openItem = new MenuItem("Open"); // menu item named openItem with
the label "Open"
MenuItem exitItem = new MenuItem("Exit");
// Add menu items to the menu
[Link](openItem);
[Link](exitItem);
// Add menu to the menu bar
[Link](fileMenu);
// Set the menu bar for the frame
[Link](menuBar);
// Add action to the Exit menu item
[Link](e -> [Link](0));
[[Link](0)-This method terminates the Java Virtual Machine (JVM) and ends the
application. 0 indicates successful termination.] [e Represents the event object
(ActionEvent) passed to the listener when the action occurs.]
[Link](300, 200);
[Link](true);
}
}
OUTPUT
The program creates a simple window titled "Simple Menu Example" with a menu bar
containing a "File" menu. The "File" menu has two options: "Open" and "Exit."