这段代码非常适合我通过以下调用来使键绑定更加愉快:
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
。 (除了文档之外,我没有看到它的任何目的。)
我想知道button.getActionCommand()
,但它会返回null
,即使我在类定义中的action(e)
之后插入此行:
setActionCommand(actionMapKey);
如何在程序中的某个位置访问操作名称?
答案 0 :(得分:1)
您必须将setActionCommand(actionMapKey);
放在构造函数中的setAction
内,而不是执行内部操作。然后您可以使用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);
}