Swing JTable-在Shift键上使用键绑定而不是KeyListener



如果以前有人回答过这个问题,我很抱歉,我试图寻找解决方案,但找不到任何相关的东西。我是新手,所以我有可能完全忽略或忽略了一些本可以让我找到简单解决方案的东西。

我已经为shift键实现了一个键监听器,这样当用户按下shift时,他会在编辑更多内容的前一行输入单元格(请查看下面的代码)。不过,有一个问题;如果用户当前正在向单元格中输入数据,则shift键不起作用,并且在调试时,我们可以看到程序甚至从未进入键侦听器。我被告知要使用密钥绑定而不是密钥侦听器来解决这个问题。我试着在网上学习一些教程,但看起来我失败了。任何帮助都将不胜感激,非常感谢!

两个关键侦听器(Tab工作正常,而Shift不工作):

table.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
//KeyCode 9 is a key code for the Tab key
if (e.getKeyCode() == 9) {
if(table.isCellEditable(table.getSelectedRow(),table.getSelectedColumn())) {
table.editCellAt(table.getSelectedRow(), table.getSelectedColumn());
} else {
table.editCellAt(table.getSelectedRow(), table.getSelectedColumn() + 1);
}
}
//The problem occurs here
//KeyCode 16 is a key code for the Shift key
if (e.getKeyCode() == 16) {
if(table.isCellEditable(table.getSelectedRow() + 1, table.getSelectedColumn())) {
table.editCellAt(table.getSelectedRow() + 1, table.getSelectedColumn());
table.setColumnSelectionInterval(table.getSelectedColumn(), table.getSelectedColumn());
table.setRowSelectionInterval(table.getSelectedRow() + 1, table.getSelectedRow() + 1);
} else {
table.editCellAt(table.getSelectedRow() + 1, table.getSelectedColumn() + 1);
table.setColumnSelectionInterval(table.getSelectedColumn() + 1, table.getSelectedColumn() + 1);
table.setRowSelectionInterval(table.getSelectedRow() + 1, table.getSelectedRow() + 1);
}
}
}
});

以下是我尝试过(但失败了)的解决方案:

class ShiftAction extends AbstractAction{
public void actionPerformed(ActionEvent ae){
System.out.println("Shift");
table.editCellAt(table.getSelectedRow() + 1, table.getSelectedColumn());
table.setColumnSelectionInterval(table.getSelectedColumn(), table.getSelectedColumn());
table.setRowSelectionInterval(table.getSelectedRow() + 1, table.getSelectedRow() + 1);
}
}
shiftAction = new ShiftAction();
table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT,KeyEvent.SHIFT_DOWN_MASK),"doShiftAction");
table.getActionMap().put("doShiftAction",shiftAction);

希望这个问题不要太愚蠢,再次提前谢谢。

e.getKeyCode() == 9

首先,不要使用幻数。阅读代码的人不知道"9"是什么意思。使用KeyEventAPI中提供的字段:KeyEvent.VK_???

我们可以看到程序甚至从未进入密钥侦听器。

焦点是用作单元格编辑器的JTextField,因此它接收KeyEvent,而不是表。

我被告知使用密钥绑定而不是密钥侦听器来解决这个问题。

您需要使用适当的InputMap。在这种情况下,它应该是:

JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT

有关详细信息,请阅读Swing教程中关于如何使用密钥绑定的部分。

最新更新