How to use Delete button on the keyboard as shortcut for delete rows from JTable [duplicate]

我的未来我决定 提交于 2019-12-02 12:55:06

This is a relatively basic concept in Swing.

You need to take a look at How to Use Key Bindings.

Essentially...

InputMap im = table.getInputMap(JTable.WHEN_FOCUSED);
ActionMap am = table.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
am.put("delete", new AbstractAction() {
    public void actionPerformed(ActionListener listener) {  
        deleteButton.doClick();
    }
});

UPDATE

There is no "default" action for delete on tables, so you can't disable it. The main problem stems from isCellEditable on the table model and cell editor. I typically have this set to return true under most circumstances.

While testing on my Mac, I found that it didn't use VK_DELETE, but used VK_BACKSPACE instead.

Once I set that up, it worked fine...

final MyTestTable table = new MyTestTable(new MyTableModel());
table.setShowGrid(true);
table.setShowHorizontalLines(true);
table.setShowVerticalLines(true);
table.setGridColor(Color.GRAY);

InputMap im = table.getInputMap(JTable.WHEN_FOCUSED);
ActionMap am = table.getActionMap();

Action deleteAction = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("I've being delete..." + table.getSelectedRow());
    }

};

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "Delete");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "Delete");
am.put("Delete", deleteAction);

setLayout(new BorderLayout());
add(new JScrollPane(table));

UPDATED

Test on Mac OS 1.7.5, JDK 7, Windows 7, JDK 6 & 7 - works fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!