Documentation

The Java™ Tutorials
Hide TOC
How to Use Actions如何使用动作
Trail: Creating a GUI With Swing
Lesson: Using Other Swing Features

How to Use Actions如何使用操作

An Action can be used to separate functionality and state from a component. Action可用于从组件中分离功能和状态。For example, if you have two or more components that perform the same function, consider using an Action object to implement the function. 例如,如果有两个或多个组件执行相同的功能,请考虑使用Action对象来实现该功能。An Action object is an action listener that provides not only action-event handling, but also centralized handling of the state of action-event-firing components such as tool bar buttons, menu items, common buttons, and text fields. Action对象是一个动作监听器,它不仅提供动作事件处理,还提供对动作事件触发组件(如工具栏按钮菜单项公共按钮文本字段)状态的集中处理。The state that an action can handle includes text, icon, mnemonic, enabled, and selected status.操作可以处理的状态包括文本、图标、助记符、启用和选定状态。

You typically attach an action to a component using the setAction method. 通常使用setAction方法将动作附加到组件。Here's what happens when setAction is invoked on a component:下面是在组件上调用setAction时发生的情况:

Here's an example of creating a tool-bar button and menu item that perform the same function:以下是创建执行相同功能的工具栏按钮和菜单项的示例:

Action leftAction = new LeftAction(); //LeftAction code is shown later
...
button = new JButton(leftAction)
...
menuItem = new JMenuItem(leftAction);

To create an Action object, you generally create a subclass of AbstractAction and then instantiate it. 要创建Action对象,通常创建AbstractAction的子类,然后实例化它。In your subclass, you must implement the actionPerformed method to react appropriately when the action event occurs. 在子类中,必须实现actionPerformed方法,以便在操作事件发生时做出适当的反应。Here's an example of creating and instantiating an AbstractAction subclass:下面是创建和实例化AbstractAction子类的示例:

leftAction = new LeftAction("Go left", anIcon,
             "This is the left button.",
             new Integer(KeyEvent.VK_L));
...
class LeftAction extends AbstractAction {
    public LeftAction(String text, ImageIcon icon,
                      String desc, Integer mnemonic) {
        super(text, icon);
        putValue(SHORT_DESCRIPTION, desc);
        putValue(MNEMONIC_KEY, mnemonic);
    }
    public void actionPerformed(ActionEvent e) {
        displayResult("Action for first button/menu item", e);
    }
}

When the action created by the preceding code is attached to a button and a menu item, the button and menu item display the text and icon associated with the action. 当前面代码创建的动作附加到按钮和菜单项时,按钮和菜单项目将显示与动作关联的文本和图标。The L character is used for mnemonics on the button and menu item, and their tool-tip text is set to the SHORT_DESCRIPTION string followed by a representation of the mnemonic key.L字符用于按钮和菜单项上的助记符,其工具提示文本设置为SHORT_DESCRIPTION字符串,后跟助记符键的表示。

For example, we have provided a simple example, ActionDemo.java, which defines three actions. 例如,我们提供了一个简单的例子ActionDemo.java,它定义了三个动作。Each action is attached to a button and a menu item. 每个动作都附加到一个按钮和一个菜单项。Thanks to the mnemonic values set for each button's action, the key sequence Alt-L activates the left button, Alt-M the middle button, and Alt-R the right button. 由于为每个按钮的动作设置了助记符值,按键序列Alt-L激活左按钮,Alt-M激活中间按钮,Alt-R激活右按钮。The tool tip for the left button displays This is the left button. Alt-L. 左侧按钮的工具提示显示“这是左侧按钮”。Alt-LAll of this configuration occurs automatically, without the program making explicit calls to set the mnemonic or tool-tip text. 所有这些配置都会自动发生,而程序无需显式调用来设置助记符或工具提示文本。As we'll show later, the program does make calls to set the button text, but only to avoid using the values already set by the actions.正如我们稍后将要展示的,程序确实会调用来设置按钮文本,但只是为了避免使用操作已经设置的值。

A snapshot of ActionDemo, which uses actions to coordinate menus and buttons.

Try this: 
  1. Click the Launch button to run ActionDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行ActionDemo(下载JDK 7或更高版本)。Or, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引

    Launches the ActionDemo example
  2. Choose the top item from the left menu (Menu > Go left).从左侧菜单中选择顶部项目(菜单>向左移动)。
    The text area displays some text identifying both the event source and the action listener that received the event.文本区域显示一些文本,标识事件源和接收事件的动作监听器。

  3. Click the leftmost button in the tool bar.单击工具栏中最左侧的按钮。
    The text area again displays information about the event. 文本区域再次显示有关事件的信息。Note that although the source of the events is different, both events were detected by the same action listener: the Action object attached to the components.请注意,尽管事件的来源不同,但这两个事件都是由同一个动作监听器检测到的:附加到组件的Action对象。

  4. Choose the top item from the Action State menu.从“操作状态”菜单中选择顶部项目。
    This disables the "Go left" Action object, which in turn disables its associated menu item and button.这将禁用“Go left”Action对象,进而禁用其关联菜单项和按钮。


Here is what the user sees when the "Go left" action is disabled:以下是用户在禁用“向左”操作时看到的内容:

A snapshot of ActionDemo when
A snapshot of ActionDemo when

Here's the code that disables the "Go left" action:下面是禁用“向左走”操作的代码:

boolean selected = ...//true if the action should be enabled;
                      //false, otherwise
leftAction.setEnabled(selected);

After you create components using an Action, you might well need to customize them. 使用Action创建组件后,您可能需要对其进行自定义。For example, you might want to customize the appearance of one of the components by adding or deleting the icon or text. 例如,您可能希望通过添加或删除图标或文本来自定义某个组件的外观。For example, ActionDemo.java has no icons in its menus, and no text in its buttons. Here's the code that accomplishes this:例如,ActionDemo.java的菜单中没有图标,按钮中没有文本。下面是实现这一点的代码:

menuItem = new JMenuItem();
menuItem.setAction(leftAction);
menuItem.setIcon(null); //arbitrarily chose not to use icon in menu
...
button = new JButton();
button.setAction(leftAction);
button.setText(""); //an icon-only button

We chose to create an icon-only button and a text-only menu item from the same action by setting the icon property to null and the text to an empty string. 我们选择通过将图标属性设置为null,将文本设置为空字符串,从同一操作中创建仅图标按钮和仅文本菜单项。However, if a property of the Action changes, the widget may try to reset the icon and text from the Action again.但是,如果Action的属性发生更改,小部件可能会再次尝试重置Action中的图标和文本。

The Action API

The following tables list the commonly used Action constructors and methods. 下表列出了常用的Action构造函数和方法。The API for using Action objects falls into three categories:使用Action对象的API分为三类:

Components that Support set/getAction支持set/getAction的组件
Class Purpose意图
AbstractButton
JComboBox
JTextField
These components and their subclasses may have an action directly assigned to them via setAction. 这些组件及其子类可能有一个通过setAction直接分配给它们的动作。For further information about components that are often associated with actions, see the sections on tool bar buttons, menu items, common buttons, and text fields. 有关经常与操作关联的组件的更多信息,请参阅工具栏按钮菜单项常用按钮文本字段部分。For details on which properties each component takes from the Action, see the API documentation for the relevant class's configurePropertiesFromAction method. 有关每个组件从Action获取哪些属性的详细信息,请参阅相关类的configurePropertiesFromAction方法的API文档。Also refer to the buttonActions table.另请参阅buttonActions表。
Creating and Using an AbstractAction创建和使用AbstractAction
Constructor or Method建造商或方法 Purpose意图
AbstractAction()
AbstractAction(String)
AbstractAction(String, Icon)
Create an Action object. 创建Action对象。Through arguments, you can specify the text and icon to be used in the components that the action is attached to.通过参数,可以指定要在操作附加到的组件中使用的文本和图标。
void setEnabled(boolean)
boolean isEnabled()
Set or get whether the components the action controls are enabled. 设置或获取操作控件的组件是否已启用。Invoking setEnabled(false) disables all the components that the action controls. 调用setEnabled(false)将禁用操作控制的所有组件。Similarly, invoking setEnabled(true) enables the action's components.类似地,调用setEnabled(true)将启用操作的组件。
void putValue(String, Object)
Object getValue(String)
Set or get an object associated with a specified key. Used for setting and getting properties associated with an action.设置或获取与指定键关联的对象。用于设置和获取与操作关联的属性。

Action Properties属性

This table defines the properties that can be set on an action. 此表定义了可以在操作上设置的属性。The second column lists which components automatically use the properties (and what method is specifically called). 第二列列出了哪些组件自动使用属性(以及具体调用的方法)。For example, setting the ACCELERATOR_KEY on an action that is then attached to a menu item, means that JMenuItem.setAccelerator(KeyStroke) is called automatically.例如,在随后附加到菜单项的操作上设置ACCELERATOR_KEY,意味着JMenuItem.setAccelerator(KeyStroke)将自动调用。

Property属性 Auto-Applied to:自动应用于:
Class
(Method Called)(调用的方法)
Purpose意图
ACCELERATOR_KEY JMenuItem
(setAccelerator)
The KeyStroke to be used as the accelerator for the action. 要用作操作加速器的KeyStrokeFor a discussion of accelerators versus mnemonics, see Enabling Keyboard Operation.有关加速器与助记符的讨论,请参阅启用键盘操作
ACTION_COMMAND_KEY AbstractButton, JCheckBox, JRadioButton
(setActionCommand)
The command string associated with the ActionEvent.ActionEvent关联的命令字符串。
LONG_DESCRIPTION None The longer description for the action. 操作的较长描述。Can be used for context-sensitive help.可用于上下文相关帮助。
MNEMONIC_KEY AbstractButton, JMenuItem, JCheckBox, JRadioButton
(setMnemonic)
The mnemonic for the action. 动作的助记符。For a discussion of accelerators versus mnemonics, see Enabling Keyboard Operation.有关加速器与助记符的讨论,请参阅启用键盘操作
NAME AbstractButton, JMenuItem, JCheckBox, JRadioButton
(setText)
The name of the action. 操作的名称。You can set this property when creating the action using the AbstractAction(String) or AbstractAction(String, Icon) constructors.您可以在使用AbstractAction(String)AbstractAction(Striing, Icon)构造函数创建操作时设置此属性。
SHORT_DESCRIPTION AbstractButton, JCheckBox, JRadioButton
(setToolTipText)
The short description of the action.动作的简短描述。
SMALL_ICON AbstractButton, JMenuItem
(setIcon)
The icon for the action used in the tool bar or on a button. 工具栏或按钮上使用的操作图标。You can set this property when creating the action using the AbstractAction(name, icon) constructor.您可以在使用AbstractAction(name, icon)构造函数创建操作时设置此属性。

Examples that Use Actions使用动作的示例

The following examples use Action objects.以下示例使用Action对象。

Example实例 Where Described描述的位置 Notes笔记
ActionDemo This section本节 Uses actions to bind buttons and menu items to the same function.使用动作将按钮和菜单项绑定到同一函数。
TextComponentDemo Text Component Features文本组件功能 Uses text actions to create menu items for text editing commands, such as cut, copy, and paste, and to bind key strokes to caret movement. 使用文本操作为文本编辑命令(如剪切、复制和粘贴)创建菜单项,并将关键笔划绑定到插入符号移动。Also implements custom AbstractAction subclasses to implement undo and redo. 还实现自定义AbstractAction子类以实现撤消和重做。The text action discussion begins in Concepts: About Editor Kits.文本操作讨论从概念:关于编辑器工具包开始。

Previous page: How to Decorate Components with the JLayer Class
Next page: How to Use Swing Timers