How to Create Menu in Swing

Menu components in Swing are subclasses of JComponent so they have all functionality of a normal Swing component.

Here are some remarkable characteristics of the Java Swing menu:

  • Menu items can have both icons and text.
  • Menu items can be checkboxes or radio buttons.
  • Each menu item can have one keyboard accelerator that display after the menu item text.
  • Almost standard Swing components can be used as menu items.

Here is the class hierarchy of Swing menu system.

Swing Menu

Create Menu Items with JMenuItem

In order to create menu items in Swing, you need to create new instances of JMenuItem and set different properties for them. You can create menu item with both text and icon.

Here are the constructors of JMenuItem:

ConstructorsDescription
JMenuItem()Creates a JMenuItem instance without icon or text.
JMenuItem(Icon icon)Creates a JMenuItem instance with a given icon.
JMenuItem(String text)Creates a JMenuItem instance with a given text.
JMenuItem(String text, Icon icon)Creates a JMenuItem instance with a given text and icon
JMenuItem(String text, int mnemonic)Creates a JMenuItem instance with the given text and keyboard mnemonic.
JMenuItem(Action a)Creates a JMenuItem instance whose properties are taken from the a given Action.

Here is the code snippet to create a menu item:

Create Menu with JMenu

After having menu items, you need to add them to a menu. In order to create a menu you need to use JMenu class. JMenu class represents the menu which can attach to a menu bar or another menu. Menu directly attached to a menu bar is known as top-level menu. If the menu is attached to a menu, it is called sub-menu.

Here are the constructors of JMenu class:

ConstructorsDescription
JMenu()Creates an instance of JMenu without text.
JMenu(String s)Creates an instance of JMenu a given text.
JMenu(String s, boolean tearOffMenu)Creates an instance of JMenu a given text. and specify the menu as a tear-off menu or not.
JMenu(Action a)Creates an instance of JMenu whose properties are taken from the specified Action.

Here is the code snippet to create a menu and add a menu item to that menu.

Create menu bar and attach it to a frame

JMenuBar class represents menu bar and can attach it to a frame. One or more menu can be added to a menu bar by using add() method. To attach menu bar to a frame you use method setJMenuBar() of frame.

Here is the menu demo application:

JMenu - Java Swing Menu

 

  • Was this tutorial helpful ?
  • YesNo