Add Images and Tooltips to Menu Items
You can add images to menu items or use images instead of text. The easiest way to add an image is to specify it when the menu item is being constructed using one of these constructors:
JMenuItem(Icon image) JMenuItem(String name, Icon image)
The first creates a menu item that displays the image specified by image. The second creates a menu item with the name specified by name and the image specified by image. For example, here the About menu item is associated with an image when it is created.
ImageIcon icon = new ImageIcon("AboutIcon.gif");
JMenuItem jmiAbout = new JMenuItem("About", icon);
After this addition, the icon specified by icon will be displayed next to the text "About" when the Help menu is displayed. This is shown in Figure 33-3. You can also add an icon to a menu item after the item has been created by calling setIcon( ), which is inherited from
AbstractButton. You can specify the horizontal alignment of the image relative to the text by calling setHorizontalTextPosition( ).
You can specify a disabled icon, which is shown when the menu item is disabled, by calling setDisabledIcon( ). Normally, when a menu item is disabled, the default icon is shown in gray. If a disabled icon is specified, then that icon is displayed when the menu item is disabled.
A tooltip is a small message that describes an item. It is automatically displayed if the mouse remains over the item for a moment. You can add a tooltip to a menu item by calling setToolTipText( ) on the item, specifying the text you want displayed. It is shown here:
void setToolTipText(String msg)
In this case, msg is the string that will be displayed when the tooltip is activated. For example, this creates a tooltip for the About item:
jmiAbout.setToolTipText("Info about the MenuDemo program.");
As a point of interest, setToolTipText( ) is inherited by JMenuItem from JComponent. This means you can add a tooltip to other types of components, such as a push button. You might want to try this on your own.
Copyright © 2018-2021 BrainKart.com; All Rights Reserved. (BS) Developed by Therithal info, Chennai.