1

我正在构建一个 InputMap 和 ActionMap 来将键绑定到方法。许多键会做类似的事情。对于每个绑定键,我在 InputMap 中有一个条目。我想将几个 InputMap 条目与同一个 ActionMap 条目相关联,并使用 AbstractAction.actionPerformed(ActionEvent event) 方法中的 ActionEvent 参数来确定按下/释放/键入了哪个键。我查看了 getID(),测试了 ActionEvent 是否是 KeyEvent(不是)。有没有办法做到这一点,或者我必须进行不同的重构,以便每个唯一的 ActionMap 条目设置一个参数,然后调用我的(参数化)方法?

这是有效的(但很冗长):

    getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),"myRightHandler");
    getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),"myLeftHandler");
    getActionMap().put("myRightHandler",new AbstractAction() {
              public void actionPerformed(ActionEvent evt) {
                  System.out.println("Typed Right Arrow");
              }
          });
    getActionMap().put("myLefttHandler",new AbstractAction() {
              public void actionPerformed(ActionEvent evt) {
                  System.out.println("Typed Left Arrow");
              }
          });

这是我想做但找不到魔法的事情:

    getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),"myGenericHandler");
    getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),"myGenericHandler");
    getActionMap().put("myGenericHandler",new AbstractAction() {
              public void actionPerformed(ActionEvent evt) {
                  // determine what key caused the event...
                  // evt.getKeyCode() does not work.
                  int keyCode = performMagic(evt);
                  switch (keyCode) {
                      case KeyEvent.VK_RIGHT:
                          System.out.println("Typed Right Arrow");
                          break;
                      case KeyEvent.VK_LEFT:
                          System.out.println("Typed Left Arrow");
                          break;
                      default:
                          System.out.println("Typed unknown key");
                          break;
                  }
              }
          };
4

1 回答 1

0

你应该先试试这个简单的逻辑。

getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),"myRightHandler");
    getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),"myLeftHandler");
    getActionMap().put("myRightHandler", new myAction("myRightHandler")); 
    getActionMap().put("myLeftHandler", new myAction("myLeftHandler")); 

    class myAction extends AbstractAction { 

        String str; 

        public myAction(String actName) {

            str = actName; 
        }

        public void actionPerformed(ActionEvent ae) { 

            switch(str) { 

                case "myRightHandler": //Here is code for 'myRightHandler'. 
                break; 

                case "myLeftHandler": //Here is code for 'myLeftHandler'. 
                break; 
                .
                .
                .
                .
                default : //Here is default Action; 
                break;
            }
        }
    } 

现在,您可以通过这种方式添加许多自定义组合键和操作,并通过 switch 区分它们。

于 2018-07-07T18:28:42.873 回答