How to use Delete button on the keyboard as shortc

2019-03-06 17:33发布

问题:

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.

回答1:

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