Sei sulla pagina 1di 13

http://docs.oracle.com/javase/tutorial/uiswing/components/menu.

html

How to Use Menus


A menu provides a space-saving way to let the user choose one of several options. Other components with which the user can make a one-of-many choice include combo boxes lists radio buttons spinners and tool bars. !f any of your menu items performs an action that is duplicated by another menu item or by a tool-bar button then in addition to this section you should read "ow to #se Actions. $enus are uni%ue in that by convention they aren&t placed with the other components in the #!. !nstead a menu usually appears either in a menu bar or as a popup menu. A menu bar contains one or more menus and has a customary platform-dependent location ' usually along the top of a window. A popup menu is a menu that is invisible until the user makes a platform-specific mouse action such as pressing the right mouse button over a popup-enabled component. (he popup menu then appears under the cursor. (he following figure shows many menu-related components: a menu bar menus menu items radio button menu items check box menu items and separators. As you can see a menu item can have either an image or text or both. )ou can also specify other properties such as font and color.

(he rest of this section teaches you about the menu components and tells you how to use various menu features:

(he menu component hierarchy

*reating menus "andling events from menu items +nabling keyboard operation ,ringing up a popup menu *ustomi-ing menu layout (he $enu A.! +xamples that use menus

The Menu Component Hierarchy


"ere is a picture of the inheritance hierarchy for the menu-related classes:

As the figure shows menu items /including menus0 are simply buttons. )ou might be wondering how a menu if it&s only a button shows its menu items. (he answer is that when a menu is activated it automatically brings up a popup menu that displays the menu items.

Creating Menus
(he following code creates the menus shown near the beginning of this menu section. (he bold lines of code create and connect the menu objects1 the other code sets up or customi-es the menu objects. )ou can find the entire program in MenuLookDemo.java. Other re%uired files are listed in the example index. Try this: *lick the 2aunch button to run the $enu2ook 3emo using 4ava5 6eb 7tart /download 438 9 or later0. Alternatively to compile and run the example yourself consult the example index.

,ecause this code has no event handling the menus do nothing useful except to look as they should. !f you run the example you&ll notice that despite the lack of custom

event handling menus and submenus appear when they should and the check boxes and radio buttons respond appropriately when the user chooses them.
//Where the GUI is created: JMenuBar menuBar; JMenu menu, submenu; JMenuItem menuItem; JRadioButtonMenuItem rbMenuItem; JCheckBoxMenuItem cbMenuItem; //Create the menu bar. menuBar = new JMenuBar(); //Bui d the !irst menu. menu = new JMenu("A Menu"); menu.setMnemonic"#e$%vent.&#'(); menu.*et(ccessib eContext").set(ccessib eDescri+tion" ,-he on $ menu in this +ro*ram that has menu items,); menuBar.add(menu); //a *rou+ o! JMenuItems menuItem = new JMenuItem("A text-only menu item", #e$%vent.&#'-); menuItem.set(cce erator"#e$.troke.*et#e$.troke" #e$%vent.&#'/, (ction%vent.(L-'M(.#)); menuItem.*et(ccessib eContext").set(ccessib eDescri+tion" ,-his doesn0t rea $ do an$thin*,); menu.add(menuItem); menuItem = new JMenuItem("Both text and icon", new ImageIcon("image !middle.gi"")); menuItem.setMnemonic"#e$%vent.&#'B); menu.add(menuItem); menuItem = new JMenuItem(new ImageIcon("image !middle.gi"")); menuItem.setMnemonic"#e$%vent.&#'D); menu.add(menuItem); //a *rou+ o! radio button menu items menu.add#e$arator(); Button1rou+ *rou+ 2 ne3 Button1rou+"); r%MenuItem = new J&adioButtonMenuItem("A radio %utton menu item"); rbMenuItem.set.e ected"true); rbMenuItem.setMnemonic"#e$%vent.&#'R); *rou+.add"rbMenuItem); menu.add(r%MenuItem); r%MenuItem = new J&adioButtonMenuItem("Another one"); rbMenuItem.setMnemonic"#e$%vent.&#'4); *rou+.add"rbMenuItem); menu.add(r%MenuItem); //a *rou+ o! check box menu items menu.add#e$arator(); c%MenuItem = new J'hec(BoxMenuItem("A chec( %ox menu item"); cbMenuItem.setMnemonic"#e$%vent.&#'C); menu.add(c%MenuItem);

c%MenuItem = new J'hec(BoxMenuItem("Another one"); cbMenuItem.setMnemonic"#e$%vent.&#'5); menu.add(c%MenuItem); //a submenu menu.add#e$arator(); u%menu = new JMenu("A u%menu"); submenu.setMnemonic"#e$%vent.&#'.); menuItem = new JMenuItem("An item in the u%menu"); menuItem.set(cce erator"#e$.troke.*et#e$.troke" #e$%vent.&#'6, (ction%vent.(L-'M(.#)); u%menu.add(menuItem); menuItem = new JMenuItem("Another item"); u%menu.add(menuItem); menu.add( u%menu); //Bui d second menu in the menu bar. menu = new JMenu("Another Menu"); menu.setMnemonic"#e$%vent.&#'7); menu.*et(ccessib eContext").set(ccessib eDescri+tion" ,-his menu does nothin*,); menuBar.add(menu); ... "rame. etJMenuBar(theJMenuBar);

As the code shows to set the menu bar for a J8rame you use the setJMenuBar method. (o add a JMenu to a JMenuBar you use the add"JMenu) method. (o add menu items and submenus to a JMenu you use the add"JMenuItem) method. Note: $enu items like other components can be in at most one container. !f you try to add a menu item to a second menu the menu item will be removed from the first menu before being added to the second. :or a way of implementing multiple components that do the same thing see "ow to #se Actions.

Other methods in the preceding code include set(cce erator and setMnemonic which are discussed a little later in +nabling 8eyboard Operation. (he set(ccessib eDescri+tion method is discussed in "ow to 7upport Assistive (echnologies.

Handling Events from Menu Items


(o detect when the user chooses a JMenuItem you can listen for action events /just as you would for a JButton0. (o detect when the user chooses a JRadioButtonMenuItem you can listen for either action events or item events as described in "ow to #se ;adio ,uttons. :or JCheckBoxMenuItems you generally listen for item events as described in "ow to #se *heck ,oxes.

Try this: *lick the 2aunch button to run the $enu 3emo using 4ava5 6eb 7tart /download 438 9 or later0. Alternatively to compile and run the example yourself consult the example index.

"ere is the code that implements the event handling:


+ub ic c ass MenuDemo ... im+ ements (ctionListener, ItemListener 9 ... +ub ic MenuDemo") 9 //...for each JMenuItem instance: menuItem.add(ctionListener"this); ... //for each JRadioButtonMenuItem: rbMenuItem.add(ctionListener"this); ... //for each JCheckBoxMenuItem: cbMenuItem.addItemListener"this); ... : +ub ic void action;er!ormed"(ction%vent e) 9 //...Get information from the action event... //...Dis !a" it in the text area... : +ub ic void item.tateChan*ed"Item%vent e) 9 //...Get information from the item event... //...Dis !a" it in the text area... :

:or examples of handling action and item events see the button radio button and check box sections as well as the list of examples at the end of this section.

Enabling

eyboard !peration

$enus support two kinds of keyboard alternatives: mnemonics and accelerators. Mnemonics offer a way to use the keyboard to navigate the menu hierarchy increasing the accessibility of programs. Accelerators on the other hand offer keyboard shortcuts to bypass navigating the menu hierarchy. $nemonics are for all users1 accelerators are for power users. A mnemonic is a key that makes an already visible menu item be chosen. :or example in MenuDemo the first menu has the mnemonic A and its second menu item has the mnemonic ,. (his means that when you run MenuDemo with the 4ava look and feel pressing the Alt and A keys makes the first menu appear. 6hile the first menu is visible pressing the , key /with or without Alt0 makes the second menu item be chosen. A menu item generally displays its mnemonic by underlining the first occurrence of the mnemonic character in the menu item&s text as the following snapshot shows.

An accelerator is a key combination that causes a menu item to be chosen whether or not it&s visible. :or example pressing the Alt and < keys in MenuDemo makes the first item in the first menu&s submenu be chosen without bringing up any menus. Only leaf menu items ' menus that don&t bring up other menus ' can have accelerators. (he following snapshot shows how the 4ava look and feel displays a menu item that has an accelerator.

setMnemonic

)ou can specify a mnemonic either when constructing the menu item or with the method. (o specify an accelerator use the set(cce erator method. "ere are examples of setting mnemonics and accelerators:

//.ettin* the mnemonic 3hen constructin* a menu item< menuItem 2 ne3 JMenuItem",( text=on $ menu item,, #e$%vent.&#'-); //.ettin* the mnemonic a!ter creation time< menuItem.setMnemonic"#e$%vent.&#'-); //.ettin* the acce erator< menuItem.set(cce erator"#e$.troke.*et#e$.troke" #e$%vent.&#'-, (ction%vent.(L-'M(.#));

As you can see you set a mnemonic by specifying the #e$%vent constant corresponding to the key the user should press. (o specify an accelerator you must use a #e$.troke object which combines a key /specified by a #e$%vent constant0 and a modifier-key mask /specified by an (ction%vent constant0. Note:

,ecause popup menus unlike regular menus aren&t always contained by a component accelerators in popup menu items don&t work unless the popup menu is visible.

"ringing Up a #opup Menu


(o bring up a popup menu / J;o+u+Menu0 you must register a mouse listener on each component that the popup menu should be associated with. (he mouse listener must detect user re%uests that the popup menu be brought up. (he exact gesture that should bring up a popup menu varies by look and feel. !n $icrosoft 6indows the user by convention brings up a popup menu by releasing the right mouse button while the cursor is over a component that is popup-enabled. !n the 4ava look and feel the customary trigger is either pressing the right mouse button /for a popup that goes away when the button is released0 or clicking it /for a popup that stays up0. Try this: *lick the 2aunch button to run the .opup$enu 3emo using 4ava5 6eb 7tart /download 438 9 or later0. Alternatively to compile and run the example yourself consult the example index.

//...#here instance varia$!es are dec!ared: J;o+u+Menu +o+u+; //...#here the GUI is constructed: //Create the +o+u+ menu. +o+u+ 2 ne3 J;o+u+Menu"); menuItem 2 ne3 JMenuItem",( +o+u+ menu item,); menuItem.add(ctionListener"this); +o+u+.add"menuItem); menuItem 2 ne3 JMenuItem",(nother +o+u+ menu item,); menuItem.add(ctionListener"this); +o+u+.add"menuItem); //(dd istener to com+onents that can brin* u+ +o+u+ menus. MouseListener +o+u+Listener 2 ne3 ;o+u+Listener"); out+ut.addMouseListener"+o+u+Listener); menuBar.addMouseListener"+o+u+Listener);

... c ass ;o+u+Listener extends Mouse(da+ter 9 +ub ic void mouse;ressed"Mouse%vent e) 9 ma$be.ho3;o+u+"e); :

+ub ic void mouseRe eased"Mouse%vent e) 9 ma$be.ho3;o+u+"e);

: +rivate void ma$be.ho3;o+u+"Mouse%vent e) 9 i! "e.is;o+u+-ri**er")) 9 +o+u+.sho3"e.*etCom+onent"), e.*et>"), e.*et?")); : :

.opup menus have a few interesting implementation details. One is that every menu has an associated popup menu. 6hen the menu is activated it uses its associated popup menu to show its menu items. Another detail is that a popup menu itself uses another component to implement the window containing the menu items. 3epending on the circumstances under which the popup menu is displayed the popup menu might implement its =window= using a lightweight component /such as a J;ane 0 a =mediumweight= component /such as a ;ane 0 or a heavyweight window /something that inherits from @indo30. 2ightweight popup windows are more efficient than heavyweight windows but prior to the 4ava 7+ .latform 9 #pdate >< release they didn&t work well if you had any heavyweight components inside your ?#!. 7pecifically when the lightweight popup&s display area intersects the heavyweight component&s display area the heavyweight component is drawn on top. (his is one of the reasons that prior to the 9u>< release we recommended against mixing heavyweight and lightweight components. !f you are using an older release and absolutely need to use a heavyweight component in your ?#! then you can invoke J;o+u+Menu.setLi*ht@ei*ht;o+u+%nab ed"!a se) to disable lightweight popup windows. :or information on mixing components in the 9u>< release and later please see $ixing "eavyweight and 2ightweight *omponents.

Customi$ing Menu %ayout


,ecause menus are made up of ordinary 7wing components you can easily customi-e them. :or example you can add any lightweight component to a JMenu or JMenuBar. And because JMenuBar uses BoxLa$out you can customi-e a menu bar&s layout just by adding invisible components to it. "ere is an example of adding a glue component to a menu bar so that the last menu is at the right edge of the menu bar:
//...create and add some menus... menuBar.add"Box.create5oriAonta 1 ue")); //...create the ri%htmost menu... menuBar.add"ri*htMenu);

Try this: *lick the 2aunch button to run the $enu?lue 3emo using 4ava5 6eb 7tart /download 438 9 or later0. Alternatively to compile and run the example yourself consult the example index.

"ere&s the modified menu layout that $enu?lue3emo displays:

Another way of changing the look of menus is to change the layout managers used to control them. :or example you can change a menu bar&s layout manager from the default left-to-right BoxLa$out to something such as 1ridLa$out. Try this: *lick the 2aunch button to run the $enu2ayout 3emo using 4ava5 6eb 7tart /download 438 9 or later0. Alternatively to compile and run the example yourself consult the example index.

"ere&s a picture of the menu layout that MenuLa$outDemo creates:

The Menu &#I


(he following tables list the commonly used menu constructors and methods. (he A.! for using menus falls into these categories:

*reating and 7etting #p $enu ,ars *reating and .opulating $enus *reating .opulating and *ontrolling .opup $enus !mplementing $enu !tems *reating and 7etting #p $enu ,ars

Constructor or Method 4$enu,ar/0 4$enu add/4$enu0 void set4$enu,ar/4$enu,ar0 4$enu,ar get4$enu,ar/0 (in J& !et, JDia!o%, J'rame,

#urpose *reates a menu bar. Adds the menu to the end of the menu bar. 7ets or gets the menu bar of an applet dialog frame internal frame or root pane.

JInterna!'rame, JRoot(ane)

*reating and .opulating $enus Constructor or Method 4$enu/0 4$enu/7tring0 4$enu/Action0 #urpose *reates a menu. (he string specifies the text to display for the menu. (he (ction specifies the text and other properties of the menu /see "ow to #se Actions0.

Adds a menu item to the current end of the menu. !f the argument is a string then the menu automatically creates a JMenuItem object that displays the specified text. 'ersion 4$enu!tem Note: ,efore >.@ the only way to associate an (ction with a add/4$enu!tem0 menu item was to use menu&s add"(ction) method to create 4$enu!tem add/7tring0 the menu item and add it to the menu. As of >.@ that method is no longer recommended. )ou can instead associate a menu item with an (ction using the set(ction method. void add7eparator/0 4$enu!tem insert/4$enu!tem int0 void insert/7tring int0 void insert7eparator/int0 void remove/4$enu!tem0 void remove/int0 void removeAll/0 Adds a separator to the current end of the menu. !nserts a menu item or separator into the menu at the specified position. (he first menu item is at position A the second at position > and so on. (he JMenuItem and .trin* arguments are treated the same as in the corresponding add methods. ;emoves the specified item/s0 from the menu. !f the argument is an integer then it specifies the position of the menu item to be removed.

*reating .opulating and *ontrolling .opup $enus Constructor or Method 4.opup$enu/0 4.opup$enu/7tring0 #urpose *reates a popup menu. (he optional string argument specifies the title that a look and feel might display as part of the popup window. Adds a menu item to the current end of the popup menu. !f the argument is a string then the menu automatically creates a JMenuItem object that displays the specified text. 'ersion Note: ,efore >.@ the only way to associate an (ction with an item in a popup menu was to use the popup menu&s add"(ction) method to create the menu item and add it to the popup menu. As of >.@ that method is no longer recommended. )ou can instead associate a menu item with an (ction using the set(ction method. Adds a separator to the current end of the popup menu.

4$enu!tem add/4$enu!tem0 4$enu!tem add/7tring0

void add7eparator/0

void insert/*omponent int0

!nserts a menu item into the menu at the specified position. (he first menu item is at position A the second at position > and so on. (he Com+onent argument specifies the menu item to add. ;emoves the specified item/s0 from the menu. !f the argument is an integer then it specifies the position of the menu item to be removed.

void remove/int0 void removeAll/0

,y default 7wing implements a menu&s window using a lightweight component. (his can cause problems if you use any heavyweight components static void in your 7wing program as described in ,ringing set2ight6eight.opup+nabled/bool #p a .opup $enu. /(his is one of several reasons ean0 to avoid using heavyweight components.0 As a workaround invoke
J;o+u+Menu.setLi*ht@ei*ht;o+u+%nab ed"!a se).

void show/*omponent int int0

3isplay the popup menu at the specified x,y position /specified in that order by the integer arguments0 in the coordinate system of the specified component. #urpose *reates an ordinary menu item. (he icon argument if present specifies the icon that the menu item should display. 7imilarly the string argument specifies the text that the menu item should display. (he integer argument specifies the keyboard mnemonic to use. )ou can specify any of the relevant B8 constants defined in the 8ey+vent class. :or example to specify the A key use #e$%vent.&#'(. (he constructor with the (ction parameter which was introduced in >.@ sets the menu item&s (ction causing the menu item&s properties to be initiali-ed from the (ction. 7ee "ow to #se Actions for details. *reates a menu item that looks and acts like a check box. (he string argument if any specifies the text that the menu item should display. !f you specify true for the boolean argument then the menu item is initially selected /checked0. Otherwise the menu item is initially unselected.

!mplementing $enu !tems Constructor or Method

4$enu!tem/0 4$enu!tem/7tring0 4$enu!tem/!con0 4$enu!tem/7tring !con0 4$enu!tem/7tring int0 4$enu!tem/Action0

4*heck,ox$enu!tem/0 4*heck,ox$enu!tem/7tring0 4*heck,ox$enu!tem/!con0 4*heck,ox$enu!tem/7tring !con0 4*heck,ox$enu!tem/7tring boolean0 4*heck,ox$enu!tem/7tring !con boolean0

4;adio,utton$enu!tem/0 4;adio,utton$enu!tem/7tring0 4;adio,utton$enu!tem/!con0 4;adio,utton$enu!tem/7tring !con0 4;adio,utton$enu!tem/7tring boolean0 4;adio,utton$enu!tem/!con boolean0 4;adio,utton$enu!tem/7tring !con boolean0 void set7tate/boolean0 boolean get7tate/0 (in JCheckBoxMenuItem) void set+nabled/boolean0

*reates a menu item that looks and acts like a radio button. (he string argument if any specifies the text that the menu item should display. !f you specify true for the boolean argument then the menu item is initially selected. Otherwise the menu item is initially unselected.

7et or get the selection state of a check box menu item. !f the argument is true enable the menu item. Otherwise disable the menu item. 7et the mnemonic that enables keyboard navigation to the menu or menu item. #se one of the B8 constants defined in the #e$%vent class. 7et the accelerator that activates the menu item. 7et the name of the action performed by the menu item.

void set$nemonic/int0 void setAccelerator/8ey7troke0 void setAction*ommand/7tring0

void Add an event listener to the menu item. 7ee addAction2istener/Action2istener0 "andling +vents from $enu !tems for details. void add!tem2istener/!tem2istener0 void setAction/Action0 7et the (ction associated with the menu item. 7ee "ow to #se Actions for details. $any of the preceding methods are inherited from (bstractButton. 7ee (he ,utton A.! for information about other useful methods that (bstractButton provides.

E(amples that Use Menus


$enus are used in a few of our examples. E(ample
MenuLookDemo

)here *escribed (his section /*reating $enus0 (his section

Notes A simple example that creates all kinds of menus except popup menus but doesn&t handle events from the menu items. Adds event handling to MenuLookDemo.

MenuDemo

/"andling +vents from $enu !tems0 ;o+u+MenuDemo (his section Adds popup menus to MenuDemo. /,ringing #p a .opup $enu0 Menu1 ueDemo (his section 3emonstrates affecting menu layout by /*ustomi-ing adding an invisible components to the $enu 2ayout0 menu bar. MenuLa$outDemo (his section !mplements sideways-opening menus /*ustomi-ing arranged in a vertical menu bar. $enu 2ayout0 Menu.e ectionMana*erDemo ' Adds highlight detection to $enu3emo. (o see this feature click a menu and then move the mouse over any menu item or submenu. Once per second the text area will be updated with information about the currently highlighted menu item not to be confused with the menu item that the user eventually chooses. (his demo uses the default Menu.e ectionMana*er which tracks the state of the menu hierarchy. (ctionDemo "ow to #se #ses (ction objects to implement Actions menu items that duplicate functionality provided by tool bar buttons. 8rame3ork ' ,rings up multiple identical frames each with a menu in its menu bar. Interna 8rameDemo "ow to #se #ses a menu item to create windows. !nternal :rames