我正在构建一个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;
                  }
              }
          };

最佳答案

您应该首先尝试这种简单的逻辑。

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进行更改。

07-24 22:20