当在 JTable
(称为 gametable
)中按下 enter 时,此代码调用例程。它运行良好,但我希望在 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了解详情。
我对您在此上下文中使用synchronized (this)
持谨慎态度;你应该在 event dispatch thread 上构建你的 GUI .
关于java - 在 JTable 中按下向上或向下时调用例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11916416/