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

  }
}

Calls:

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 key name, WHATEVER, either intelligently or otherwise, elsewhere in a program.

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

    setActionCommand(actionMapKey);

What is the purpose of the key name? Am I supposed to use it somewhere in a program other than in defining the key binding?

Nic
  • 6,211
  • 10
  • 46
  • 69
DSlomer64
  • 4,234
  • 4
  • 53
  • 88
  • Why do we care if the question was edited? Just change your question. You don't need to make the changes big and bold. – Nic Jun 18 '15 at 20:22

1 Answers1

1

The key name is used if you have only one listener to the events.

Usually:

 setOnKeyListener(new OnKeyListener(){
     void onKeyPressed(KeyEvent k){
            if(k.getKey() == KeyEvent.VK_ENTER)
                  //Handle ENTER key
            if(k.getKey() == KeyEvent.VK_ESCAPE)
                  //Handle ESC key
     }
);

This code was wrote from my memory, probably is not the actual Object names from the Java API.

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
  • @Marcos--I didn't ask what I intended to. I've asked this question again with a different title and slightly different content. – DSlomer64 Jun 21 '15 at 17:57
  • @Marcos--The new thread with the answer I was looking for is [here](http://stackoverflow.com/questions/30967709/how-do-i-access-the-name-of-the-action-defined-in-a-java-key-binding/30967930#30967930) – DSlomer64 Jun 23 '15 at 16:26