I have a program with an editable JTable
. I am attempting to create a key binding for the table that will delete the rows selected by the user when the Delete
key is pressed. This is the code for my key binding:
inventoryTable.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
inventoryTable.getActionMap().put("delete", new RemoveSelectedAction());
However, when I press the Delete
key while one or more rows are selected, no rows are deleted, and the selected cell displays its editor.
Having looked at the answers here and here, I suspect the problem is this: because my table is editable, the selected cell is intercepting the keypress before it reaches the JTable
's key binding.
- Am I correct in my assessment of why the
Delete
key is not behaving as desired? - How do I get the keypress to reach the
JTable
's binding?
UPDATE: When I changed my table model's isCellEditable
method to return false
for all cells, the key binding worked as expected, so I am now almost certain that the problem is the keypress being intercepted by the selected cell.
This is the code that produces the problem:
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();
}
});
}
}