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 code is also very simple :
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
int[] selectedRows = table.getSelectedRows();
for (int i = selectedRows.length - 1; i > -1; i--) {
tableModel.removeRow(selectedRows[i]);
}
The problem is that after the deletion gets finished we’ll hear a sound beep (I’m on windows, typical windows beep), as when pressing the delete key in an empty text box (or when the caret is at the end of the text).
What I thing is happening is that the key press is dispatched further to the text component that displays the text content of the cell(the first cell after the deleted ones). The beep is fired by the DefaultEditorKit$DeleteNextCharAction#actionPerformed method because there is no character ahead the dot.
As a hack I modify the event in the listener :
e.setKeyCode(KeyEvent.VK_SHIFT) // see JTable#processKeyBinding
the event does not get forwarded further, so the beep dissapear but I think it’s a bad solution and there’s a better one. But which is that better solution ?
Use key bindings instead…
(I borrowed mKorbel data for my test, so my test was using a
DefaultTableModel, you will need to cast to the model you are using).Also, if you editing, this may still fire, so you will need to check for that