Java Reference
In-Depth Information
public void actionPerformed(ActionEvent actionEvent) {
Runnable runnable = new Runnable() {
public void run() {
JOptionPane.showMessageDialog(
parentComponent, "About Swing",
"About Box V2.0", JOptionPane.INFORMATION_MESSAGE);
}
};
EventQueue.invokeLater(runnable);
}
}
The next source creates a
ShowAction
and a
JMenuItem
for the File and Edit menus in the
sample program (Listing 6-1). Without explicitly setting the menu item properties, it will then
have an “About” text label and an
A
mnemonic, and will perform the defined
actionPerformed()
method as its
ActionListener
. In fact, you can create the
Action
once, and then associate it
with as many places as necessary (or other components that support adding
Action
objects).
Action showAction = new ShowAction(aComponent);
JMenuItem fileAbout = new JMenuItem(showAction);
fileMenu.add(fileAbout);
JMenuItem editAbout = new JMenuItem(showAction);
editMenu.add(editAbout);
One complexity-busting side effect when using
AbstractAction
is that it lets you disable
the
Action
with
setEnabled(false)
, which, in turn, will disable all components created from it.
JMenu Properties
Besides the 100-plus inherited properties of
JMenu
, 16 properties are available from
JMenu
-specific
methods, as shown in Table 6-5. Several of the properties override the behavior of the inherited
properties. For instance, the setter method for the
accelerator
property throws an error if you
try to assign such a property. In other words, accelerators aren't supported within
JMenu
objects.
The remaining properties describe the current state of the
JMenu
object and its contained menu
components.
Table 6-5.
JMenu Properties
Property Name
Data Type
Access
accelerator
KeyStroke
Write-only
accessibleContext
AccessibleContext
Read-only
component
Component
Read-only
delay
int
Read-write
itemCount
int
Read-only
menuComponentCount
int
Read-only
menuComponents
Component[ ]
Read-only