Java Reference
In-Depth Information
JMenu fileMenu = new JMenu("File");
JMenuItem newMenuItem = new JMenuItem("New");
fileMenu.add(newMenuItem);
JMenuItem openMenuItem = new JMenuItem("Open");
fileMenu.add(openMenuItem);
JMenuItem closeMenuItem = new JMenuItem("Close");
fileMenu.add(closeMenuItem);
fileMenu.addSeparator();
JMenuItem saveMenuItem = new JMenuItem("Save");
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
JMenuItem exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
Notice the
addSeparator()
calls wrapped around the call to add the Save menu item.
In addition to adding menu items at the end of a menu, you can insert them at specific
positions or insert a separator at a specific position, as follows:
public JMenuItem insert(JMenuItem menuItem, int pos);
public JMenuItem insert(Action a, int pos);
public void insertSeparator(int pos);
When a menu item is added to a
JMenu
, it's added to an internal
JPopupMenu
.
Using Action Objects with Menus
The
Action
interface and its associated classes are described in Chapter 2. An
Action
is an
extension of the
ActionListener
interface and contains some special properties for customizing
components associated with its implementations.
With the help of the
AbstractAction
implementation, you can easily define text labels,
icons, mnemonics, tooltip text, enabled status, and an
ActionListener
apart from a component.
Then you can create a component with an associated
Action
and not need to give the component
a text label, icon, mnemonics, tooltip text, enabled status, or
ActionListener
, because those
attributes would come from the
Action
. For a more complete description, refer to Chapter 2.
To demonstrate, Listing 6-2 creates a specific implementation of
AbstractAction
and adds
it to a
JMenu
multiple times. Once the
Action
is added to a
JMenu
, selecting the
JMenuItem
will
display a pop-up dialog box with the help of the
JOptionPane
class, a topic covered in Chapter 9.
Listing 6-2.
About Action Definition
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ShowAction extends AbstractAction {
Component parentComponent;
public ShowAction(Component parentComponent) {
super("About");
putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_A));
this.parentComponent = parentComponent;
}