I needed to delete rows from a JTable on the delete key-press. So the use case is quite simple, the user select some rows, press the delete key, the rows get deleted. The co
This is MadProgrammer's code but I modified it to work with multiple selected rows at once instead of one by one:
// Assume table is a JTable instance
InputMap inputMap = table.getInputMap(JTable.WHEN_FOCUSED);
ActionMap actionMap = table.getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "DeleteRow");
actionMap.put("DeleteRow", new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
int[] row = table.getSelectedRows();
for (int i = 0; i < row.length; i++)
{
((DefaultTableModel) table.getModel()).removeRow(row[i] - i * 1);
}
}
});