我知道我可以使用KeyListener来检查是否按下DELETE (char) 127
,但是如何将keyListener添加到JTable中的selectedRow?
修改
我试过这个,但它不起作用:
myTable.addKeyListener(this);
...
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == 127 && myTable.GetSelectedRow() != -1)
{
btnRemove.doClick(); // this will remove the selected row in JTable
}
}
答案 0 :(得分:10)
KeyListeners的一个问题是,正在侦听的组件必须具有焦点。解决这个问题的一种方法是使用Key Bindings。
如,
// assume JTable is named "table"
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = table.getInputMap(condition);
ActionMap actionMap = table.getActionMap();
// DELETE is a String constant that for me was defined as "Delete"
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), DELETE);
actionMap.put(DELETE, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
// TODO: do deletion action here
}
});
答案 1 :(得分:3)
您无需在行中添加一个。只需在表中添加一个监听器,让它询问表中选择哪一行。
您也可以尝试使用keyTyped
代替keyPressed
。有些平台存在问题,其中一个有效,另一个没有。
如果您想让用户配置他们的密钥绑定,您可以像@hovercraft建议并使用密钥绑定。它需要将KeyStroke
映射到具有InputMap
的操作名称,并将操作名称与Action
映射到ActionMap
。
table.getInputMap().put(KeyStroke.getKeyStroke("DELETE"),
"deleteRow");
table.getActionMap().put("deleteRow", yourAction);
答案 2 :(得分:0)
您将KeyListener
添加到JTable
如下:
table.addKeyListener(new KeyAdapter()
{
@Override
public void keyReleased(KeyEvent keyEvent)
{
considerDeletingSelectedRows(keyEvent, table);
}
});
private void considerDeletingSelectedRows(KeyEvent keyEvent, JTable table)
{
int keyCode = keyEvent.getKeyCode();
int[] selectedRows = table.getSelectedRows();
int selectedRowsCount = selectedRows.length;
if (keyCode == KeyEvent.VK_DELETE && selectedRowsCount > 0)
{
// Perform actual row deletion
}
}
要删除选定的行,您可以签出this答案。