Java Swing | JMenuBar
JMenuBar, JMenu and JMenuItems are a part of Java Swing package. JMenuBar is an implementation of menu bar . the JMenuBar contains one or more JMenu objects, when the JMenu objects are selected they display a popup showing one or more JMenuItems .
JMenu basically represents a menu . It contains several JMenuItem Object . It may also contain JMenu Objects (or submenu).
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- JMenuBar() : Creates a new MenuBar.
- JMenu() : Creates a new Menu with no text.
- JMenu(String name) : Creates a new Menu with a specified name.
- JMenu(String name, boolean b) : Creates a new Menu with a specified name and boolean
value specifies it as a tear-off menu or not. A tear-off menu can be opened and dragged away from its parent menu bar or menu.
Commonly used methods:
- add(JMenu c) : Adds menu to the menu bar. Adds JMenu object to the Menu bar.
- add(Component c) : Add component to the end of JMenu
- add(Component c, int index) : Add component to the specified index of JMenu
- add(JMenuItem menuItem) : Adds menu item to the end of the menu.
- add(String s) : Creates a menu item with specified string and appends it to the end of menu.
- getItem(int index) : Returns the specified menuitem at the given index
The following programs will illustrate the use of JMenuBar
1. Program to make a MenuBar and add menu items to it
2. Program to add a menubar and add menuitems, submenu items and also add ActionListener to menu items
Note : The following program might not run in an online compiler, please use an offline IDE.