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

橙三吉。 提交于 2019-12-04 06:51:36

问题


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



来源:https://stackoverflow.com/questions/13238585/how-to-use-delete-button-on-the-keyboard-as-shortcut-for-delete-rows-from-jtable

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