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