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 ancestorIm = son.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).
//get WHEN_IN_FOCUSED_WINDOW inputMap windowIm = son.getInputMap(WHEN_IN_FOCUSED_WINDOW). 在这些InputMap中分别加入键盘绑定: focusIm.put(KeyStroke.getKeyStroke( f ),"actionFocusSon"). focusFatherIm.put(KeyStroke.getKeyStroke( F ),"actionFocusFather"). ancestorIm.put(KeyStroke.getKeyStroke( a ),"actionAncestor"). windowIm.put(KeyStroke.getKeyStroke( w ),"actionWindow"). 得到son组件的缺省的ActionMap,并将已经建立的行为与特定的对象(字符串)进行绑定: am = son.getActionMap().
am.put("actionFocusSon",whenFocusSon). am.put("actionFocusFather",whenFocusFather). am.put("actionAncestor",ancestor). am.put("actionWindow",window).
|