如何访问 Java 键绑定中定义的操作名称?

How do I access the name of the action defined in a Java key binding?

这段代码对我来说效果很好,可以通过以下调用使键绑定更愉快:

import java.awt.event.ActionEvent;
import javax.swing.*;
import static javax.swing.KeyStroke.getKeyStroke;

public abstract class KeyBoundButton extends JButton{

  public abstract void action(ActionEvent e);

  public KeyBoundButton(String actionMapKey, int key, int mask)
  {
    Action myAction = new AbstractAction()
    {
      @Override public void actionPerformed(ActionEvent e)
      {
        action(e);
      }
    };  

    setAction(myAction);

    getInputMap(WHEN_IN_FOCUSED_WINDOW)
                  .put(getKeyStroke(key, mask),actionMapKey);
    getActionMap().put(                        actionMapKey, myAction);

  }
}

典型调用:

button = new KeyBoundButton("WHATEVER", VK_X, CTRL_DOWN_MASK) 
{
  @Override 
  public void action(ActionEvent e)
  {
    JOptionPane.showMessageDialog(null,"Ctrl-X was pressed");
  }
};

但我不知道如何在程序的其他地方智能地或以其他方式使用操作名称 WHATEVER。 (除了文档之外,我看不到它有任何用途。)

我想知道 button.getActionCommand() 但它 returns null,即使我在 class 定义中的 action(e) 之后插入此行:

    setActionCommand(actionMapKey);

如何访问程序中某处的操作名称?

您必须将 setActionCommand(actionMapKey); 放在构造函数中的 setAction 之后,而不是在执行的操作中。然后您可以使用 getActionCommand()

访问该值
 public KeyBoundButton(String actionMapKey, int key, int mask)
  {
    Action myAction = new AbstractAction()
    {
      @Override public void actionPerformed(ActionEvent e)
      {
        action(e);
      }
    };  

    setAction(myAction);
 setActionCommand(actionMapKey);//like this
 System.out.println(getActionCommand());
    getInputMap(WHEN_IN_FOCUSED_WINDOW)
                  .put(getKeyStroke(key, mask),actionMapKey);
    getActionMap().put(                        actionMapKey, myAction);

  }