How do I use key name in key bindings?

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

  }
}

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?

1

There are 1 answers

2
Marcos Vasconcelos On

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.