java-在JTable中按下向上或向下键时调用例程
作者:互联网
当在JTable中按下Enter键时,此代码调用例程(称为gametable).它运行良好,但是我希望在JTable中向上或向下移动时调用相同的Action,而无需按Enter.我无法正常工作.我尝试用VK_UP替换VK_ENTER,但无法在桌子上上下移动吗?
KeyStroke enter = KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER, 0);
gameTable.getJTable().unregisterKeyboardAction(enter);
gameTable.getJTable().registerKeyboardAction(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
synchronized (this) {
gotoGame(gameTable.getSelectedIndex());
}
}
}, enter, JComponent.WHEN_FOCUSED);
我不知道.有人能帮我吗?
解决方法:
您必须将步骤分开:
>首先将两个KeyStroke实例放入InputMap中,以便它们以相同的actionMapKey为目标:
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
KeyStroke up = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
String actionMapKey = "anActionMapKey";
gameTable.getInputMap().put(enter, actionMapKey);
gameTable.getInputMap().put(up, actionMapKey);
>然后将该actionMapKey与您的Action相关联:
gameTable.getActionMap().put(actionMapKey, new AbstractAction(actionMapKey) {
...
});
有关详细信息,请参见How to Use Actions和Key Bindings.
我警告您在此情况下使用同步的(this);您应该在event dispatch thread上构建GUI.
标签:swing,jtable,key-bindings,keystrokes,java 来源: https://codeday.me/bug/20191127/2076967.html