I have to delete a selected row in JTable using the Key Event. When I select a row and press the Delete Key, the selected row values should be deleted. How can I do this?
Asked
Active
Viewed 4,243 times
-1
-
If you ask further questions you should post more of what you already tried so people don't feel like they have to do the thinking for you. Also, you may want to read http://tinyurl.com/so-hints – Angelo Fuchs Apr 13 '12 at 06:56
-
@AngeloNeuschitzer: No need to shrink [*Jon Skeet: Coding Blog*](http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx); see [*How can I format and link in comments?*](http://meta.stackexchange.com/q/19756/163188) for details. – trashgod Apr 13 '12 at 09:58
1 Answers
1
You have to get the selected Rows (thats where the curser currently is) and then call removeRow on that rows.
I recommend you read the API for JTable.
try this (I used multiple rows in the code where I used it, but you should be able to break it down to one. Also, I'm unsure if the Arrays.sort is really necessary)
int [] toDelete = dataTable.getSelectedRows();
Arrays.sort(toDelete); // be shure to have them in ascending order.
MyTableModel myTableModel = (MyTableModel)dataTable.getModel();
for(int ii = toDelete.length -1; ii >=0; ii--) {
myTableModel.removeRow(toDelete[ii]); // beginning at the largest.
}

Angelo Fuchs
- 9,825
- 1
- 35
- 72
-
You need to convert to model indexes, as shown in more recent [`JTable`](http://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html) documentation. Better: use a `ListSelectionListener` mentioned [here](http://stackoverflow.com/a/10130736/230513). – trashgod Apr 13 '12 at 10:10
-
@trashgod thanks, I'll take a look into it when I touch that code of mine the next time. – Angelo Fuchs Apr 13 '12 at 10:41
-
Yes, the problem might be inapparent in code without a `RowSorter` (or a pre-1.6 alternative). – trashgod Apr 13 '12 at 16:31