如何访问在Java键绑定中定义的操作的名称? [英] How do I access the name of the action defined in a Java key binding?
问题描述
此代码对我来说非常有效,可以通过诸如以下的调用使键绑定更加令人愉悦:
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);
}
}
典型呼叫:
button = new KeyBoundButton("WHATEVER", VK_X, CTRL_DOWN_MASK)
{
@Override
public void action(ActionEvent e)
{
JOptionPane.showMessageDialog(null,"Ctrl-X was pressed");
}
};
但是我不知道如何智能地或其他方式在程序的其他地方使用动作名称WHATEVER
. (除了文档,我看不到其他目的.)
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.)
我想知道button.getActionCommand()
,但是即使我在类定义的action(e)
之后插入了这行,它也会返回null
:
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?
推荐答案
您必须将setActionCommand(actionMapKey);
放在setAction
之后,而不是在内部执行操作.然后,您可以使用getActionCommand()
访问值>
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);
}
这篇关于如何访问在Java键绑定中定义的操作的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!