如何通过按键盘上的DELETE删除JTable中的一行

我知道我可以使用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 } } 

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 } }); 

您不需要在行中添加一个。 只需向表中添加一个侦听器,让它询问表中选择哪一行。

您也可以尝试使用keyTyped而不是keyPressed 。 有些平台有问题,其中一个工作,另一个没有。

如果您想让用户配置他们的密钥绑定,您可以像@hovercraft建议并使用密钥绑定。 它需要使用其InputMapKeyStroke映射到动作名称,并使用ActionMap将动作名称映射到Action

 table.getInputMap().put(KeyStroke.getKeyStroke("DELETE"), "deleteRow"); table.getActionMap().put("deleteRow", yourAction);