本文介绍了如何通过按键盘上的DELETE删除JTable中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用KeyListener来检查是否按下DELETE (char)127 ,但是如何将keyListener添加到JTable中的selectedRow?

I know that I can use KeyListener to check if DELETE (char) 127 is pressed or not, but how can I add keyListener to the selectedRow in JTable?

编辑:

我试过这个但它不起作用:

I have tried this but it doesn't work:

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。

One issue with KeyListeners is that the component being listened to must have the focus. One way to get around this is to use 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
     }
  });

这篇关于如何通过按键盘上的DELETE删除JTable中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 07:05