如何使用键盘上的“删除”按钮作为从JTable中删除行的快捷方式 [英] How to use Delete button on the keyboard as shortcut for delete rows from JTable
问题描述
可能重复:
如何使删除按钮删除JTable中的行?
我想要使用键盘上的删除按钮从JTable中删除行。我的GUI上有删除按钮,只想要快捷方式。我也做了击键但问题是,当我选择一些行删除实际上默认情况下在表中删除按钮用于输入当前单元格。我想禁用此快捷方式并使删除按钮删除所选行。
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.
推荐答案
这是Swing中一个相对基本的概念。
This is a relatively basic concept in Swing.
你需要看看如何使用键绑定。
基本上......
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();
}
});
更新
表上没有删除的默认操作,因此您无法禁用它。主要问题源于表模型和单元格编辑器上的 isCellEditable
。在大多数情况下,我通常会将此设置返回true。
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.
在Mac上进行测试时,我发现它没有使用 VK_DELETE
,但是使用了 VK_BACKSPACE
。
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));
更新
在Mac OS 1.7.5,JDK 7,Windows 7,JDK 6& 7 - 工作正常
Test on Mac OS 1.7.5, JDK 7, Windows 7, JDK 6 & 7 - works fine
这篇关于如何使用键盘上的“删除”按钮作为从JTable中删除行的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!