我有一个可编辑JTable
的程序。我正在尝试为表创建一个键绑定,该键将在按下Delete
键时删除用户选择的行。这是我的密钥绑定的代码:
inventoryTable.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
inventoryTable.getActionMap().put("delete", new RemoveSelectedAction());
但是,当我在选择一行或多行时按Delete
键时,不会删除任何行,并且所选单元格会显示其编辑器。
看了答案here和here,我怀疑问题是这样的:因为我的表格是可编辑的,所选的单元格在到达JTable
之前拦截了按键#39; s键绑定。
Delete
键不符合要求时,我是否正确?JTable
的绑定? 更新:当我将表格模型的isCellEditable
方法更改为return false
所有单元格时,键绑定按预期工作,所以我现在几乎确定问题是所选单元格截获的按键。
这是产生问题的代码:
import javax.swing.*;
import java.awt.event.*;
public class TableDeleteRowsTest extends JFrame
{
public TableDeleteRowsTest()
{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
String[] columnNames = { "A", "B", "C" };
Object[][] data = {
{ "foo", "bar", "baz" },
{ 1, 2, 3 }
};
JPanel contentPane = new JPanel();
JTable table = new JTable(data, columnNames);
table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
table.getActionMap().put("delete", new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("In the actual program, this will delete the rows currently selected by the user.");
}
});
contentPane.add(table);
contentPane.setOpaque(true);
setContentPane(contentPane);
}
public static void createAndShowGUI()
{
TableDeleteRowsTest test = new TableDeleteRowsTest();
test.pack();
test.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}