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

91 views Asked by At

This code works well for me to make key bindings more pleasant, via calls such as those that follow:

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);

  }
}

Typical call:

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

But I don't have a clue how to use the action name, WHATEVER, either intelligently or otherwise, elsewhere in a program. (I don't see any purpose for it other than documentation.)

I wondered about button.getActionCommand() but it returns null, even if I insert this line after action(e) in the class definition:

    setActionCommand(actionMapKey);

How would I access the action name somewhere in a program?

1

There are 1 answers

4
Madhan On BEST ANSWER

You have to put the setActionCommand(actionMapKey); after setAction inside the constructor not inside action performed..Then you can access the value using 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);

  }