简体   繁体   中英

How do I use key name in key bindings?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM