0

Possible Duplicate:
How to make delete button to delete rows in JTable?

Exact Duplicate to How to make delete button to delete rows in JTable?

I want to use Delete button on the keyboard to delete rows from JTable. I have delete button on my GUI and only want shortcut. Also I made the keystroke but the problem is that when I select some row to delete in fact by default in the table delete button is used to enter in the current cell. I want to disable this shortcut and make delete button to delete the selected rows.

Community
  • 1
  • 1
user1761818
  • 365
  • 1
  • 7
  • 14
  • What prevents you from deleting selected rows in table? – Roman C Nov 05 '12 at 19:12
  • SO isn't code generator, again for better helps sooner post an [SSCCE](http://example.com) , demonstrated described issue, possible duplicate with another users question – mKorbel Nov 05 '12 at 19:28
  • A general approach is shown [here](http://stackoverflow.com/a/13240106/230513). – trashgod Nov 05 '12 at 21:03
  • It's a question not to make a delete button/action/keystroke but how to actually do it may be by using events or smth. – Roman C Nov 05 '12 at 21:07

1 Answers1

6

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366