Java Reference
In-Depth Information
public JMenu()
JMenu jMenu = new JMenu();
public JMenu(String label)
JMenu jMenu = new JMenu("File");
public JMenu(String label, boolean useTearOffs)
public JMenu(Action action)
Action action = ...;
JMenu jMenu = new JMenu(action);
One constructor is for using a tear-off menu. However, tear-off menus aren't currently
supported; therefore, the argument is ignored. The fourth constructor pulls the properties of
the menu from an Action .
Note Tear-off menus are menus that appear in a window and remain open after selection, instead of
automatically closing.
Adding Menu Items to a JMenu
Once you have a JMenu , you need to add JMenuItem objects to it; otherwise, the menu will not
display any choices. There are five methods for adding menu items defined within JMenu and
one for adding a separator:
public JMenuItem add(JMenuItem menuItem);
public JMenuItem add(String label);
public Component add(Component component);
public Component add(Component component, int index);
public JMenuItem add(Action action);
public void addSeparator();
In Listing 6-1 earlier in this chapter, all the JMenuItem components were added to JMenu
components with the first add() method. As a shortcut, you can pass the text label for a JMenuItem
to the add() method of JMenu . This will create the menu item, set its label, and pass back the
new menu item component. You can then bind a menu item event handler to this newly
obtained menu item. The third add() method shows that you can place any Component on a
JMenu , not solely a JMenuItem . The fourth add() lets you position the component. The last add()
variety, with the Action argument, will be discussed in the next section of this chapter.
You can add separator bars with the addSeparator() method of JMenu . For instance, in
Listing 6-1, the File menu was created with code similar to the following:
 
Search WWH ::




Custom Search