This section provides a tutorial example on how to use the javax.swing.JMenu class to create multiple menus and how to add them to the menu bar. Sub menus and menu items added to a menu will be listed vertically when the menu is selected.
Here is an example program I wrote to test the JMenu class:
/**
* JMenuTest.java
* Copyright (c) 2009 by Dr. Herong Yang, http://www.herongyang.com/
*/
import javax.swing.*;
public class JMenuTest {
JFrame myFrame = null;
public static void main(String[] a) {
(new JMenuTest()).test();
}
private void test() {
myFrame = new JFrame("Menu Test");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setBounds(50,50,250,150);
myFrame.setContentPane(new JDesktopPane());
JMenuBar myMenuBar = new JMenuBar();
JMenu myMenu = getFileMenu();
myMenuBar.add(myMenu);
myMenu = getColorMenu();
myMenuBar.add(myMenu);
myFrame.setJMenuBar(myMenuBar);
myFrame.setVisible(true);
}
private JMenu getFileMenu() {
JMenu myMenu = new JMenu("File");
JMenu mySubMenu = getOpenMenu();
myMenu.add(mySubMenu);
JMenuItem myItem = new JMenuItem("Close");
myMenu.add(myItem);
myMenu.addSeparator();
myItem = new JMenuItem("Exit");
myMenu.add(myItem);
return myMenu;
}
private JMenu getColorMenu() {
JMenu myMenu = new JMenu("Color");
JMenuItem myItem = new JMenuItem("Red");
myMenu.add(myItem);
myItem = new JMenuItem("Green");
myMenu.add(myItem);
myItem = new JMenuItem("Blue");
myMenu.add(myItem);
return myMenu;
}
private JMenu getOpenMenu() {
JMenu myMenu = new JMenu("Open");
JMenuItem myItem = new JMenuItem("Java");
myMenu.add(myItem);
myItem = new JMenuItem("HTML");
myMenu.add(myItem);
myItem = new JMenuItem("GIF");
myMenu.add(myItem);
return myMenu;
}
}
If you run this example, you will see the frame window shows up with the menu bar like this:
Interesting notes about this tutorial example:
Multiple menus can be added to a menu bar. The "File" menu and the "Color" menu are added to the menu bar in this example.
A menu can have a child menu included in the same way as a menu item. The "Open" menu is added as a child menu to the "File" menu in this example.
Call the addSeparator() method on a JMenu object does add a separation line in the menu element list.
Sample programs listed in this section have been tested with JDK 1.6.0.