JMenu, JMenuBar and JMenuItem – Java Swing – Example
In this tutorial, we are going to see an example of JMenu, JMenuBar and JMenuItem in Java Swing. JMenuBar class is used to display the menu bar on the window. It can have multiple menus.
JMenu class object is used to create a drop-down menu that is displayed from the menu bar. It inherits from JMenuItem class.
The object of JMenuItem class adds a simple item to the menu. The items used in a menu must belong to JMenuItem or to one of its subclasses.
[st_adsense]
List of constructors:
JMenuBar() | Create a new menu bar. |
JMenu() | Create a new menu without text. |
JMenu(String name) | Create a new menu with a specified name. |
JMenu(String name, boolean b) | Creates a new menu with a specified name and a boolean |
Commonly used methods:
- add(JMenu c) : Adds a menu (JMenu object) to the menu bar.
- add(Component c) : Add a component at the end of JMenu.
- add(Component c, int index) : Adds a component to the specified index of JMenu.
- add(JMenuItem menuItem) : Adds a menu item at the end of the menu.
- add(String s) : Creates a menu item with the specified string and appends it to the end of the menu.
- getItem(int index) : Returns the specified element at the given index.
Example of JMenu, JMenuBar and JMenuItem in Java Swing:
import javax.swing.*; class MyMenu { JMenu menu, smenu; JMenuItem e1, e2, e3, e4, e5, e6; MyMenu() { // Create the frame JFrame frame = new JFrame("Menu Example"); // Create the menu bar JMenuBar menubar = new JMenuBar(); // Create menu menu = new JMenu("Menu"); // Create the sub menu smenu = new JMenu("Sub menu"); // Create menu and submenu items e1 = new JMenuItem("Item 1"); e2 = new JMenuItem("Item 2"); e3 = new JMenuItem("Item 3"); e4 = new JMenuItem("Item 4"); e5 = new JMenuItem("Item 5"); e6 = new JMenuItem("Item 6"); // Add items to menu menu.add(e1); menu.add(e2); menu.add(e3); // Add items to the submenu smenu.add(e4); smenu.add(e5); smenu.add(e6); // Add the submenu to the main menu menu.add(smenu); // Add the menu to the menu bar menubar.add(menu); // Add the menu bar to the frame frame.setJMenuBar(menubar); frame.setSize(300,300); frame.setLayout(null); frame.setVisible(true); } public static void main(String args[]) { new MyMenu(); } }
Output:
[st_adsense]