background image

设置它的 parent 属性。ActionMap 也具有相同的 parent 属性,使用方法也相同。
  以上是如何将一个键盘事件对应到一个行为,以下就简单介绍行为(Action)。
  行为是一个实现了 Action 接口的类。在 Action 接口中定义了 7 个方法。其中最关键
的是 actionPerformed()方法。这个方法描述了这个行为的具体操作过程。其他几个方法

setEnabled,isEnabled,putValue,getValue,addPropertyChangeListener,和
removePropertyChangeListener 方法。他们分别用来设置行为是否可用、判断行为可
用的状态、设置和取得行为的一些属性,最后两个方法用来允许其他对象在行动对象的属
性发生变化后得到通知。
  通常我们使用一个实现了 Action 接口的大部分方法的抽象类 AbstractAction 类作
为基类,重载 actionPerformed 方法以实现我们的行为。
  我们用一个例子来具体说明如何进行实际的操作。

 

  首先编写一个具体的行为,对指定的键盘事件进行处理:
  public class TextAction extends AbstractAction
  {
  private String a;
  public TextAction(String a)
  { this.a = a; }
  public void actionPerformed(ActionEvent parm1)
  {
  String b = parm1.getActionCommand(); //得到行为的命令字符串

  System.out.println("command="+b);
  System.out.println("prompt="+this.a);
  }
  }

  建立四个 TextAction 对象:
  TextAction whenFocusSon = new TextAction("focus son");
  TextAction whenFocusFather = new TextAction("focus father");
  TextAction window = new TextAction("window");
  TextAction ancestor = new TextAction("ancestor");

    随 后 , 在 一 个 窗 体 中 加 入 两 个 面 板 , 名 为 sonPanel 和 parentPanel , 使 得
parentPanel 是 sonPanel 的祖先。并在 sonPanel 中加入一个名为 son 的 button,在
parentPanel 中加入名为 parent 的 button。在 fatherPanel 外加入几个 button。
  得到 son 组件的三个 InputMap,并创建一个名为 focusFatherIm 的 InputMap,
使得这个 InputMap 成为 focusIm 的 parent:
  //get default inputMap (when focus inputmap) and set a parent InputMap

  focusIm = son.getInputMap();
  focusFatherIm = new InputMap();
  focusIm.setParent(focusFatherIm);
  //get WHEN_ANCESTOR_OF_FOCUSED_COMPONENT inputMap