0

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?

DSlomer64
  • 4,234
  • 4
  • 53
  • 88

1 Answers1

1

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

  }
Madhan
  • 5,750
  • 4
  • 28
  • 61
  • If I add the line below to just after `setAction`, it displays ``. `System.out.println("<" + getActionCommand() + ">");` – DSlomer64 Jun 21 '15 at 18:38
  • @DSlomer64 Now try I have added after `setAction`.It will work now – Madhan Jun 21 '15 at 18:45
  • Thanks. I would swear that I had already tried that once before, but whatever I did, I obviously didn't do it right. – DSlomer64 Jun 21 '15 at 19:23
  • P.S. I can refer to it like so: `JOptionPane.showMessageDialog(null,"Ctrl-X was pressed " + getActionCommand());` in the definition of `button`. – DSlomer64 Jun 21 '15 at 19:26