Hamza Yerlikaya
Hamza Yerlikaya

Reputation: 49329

getting selected row through AbstractTableModel

Is it possible to get the selected row index from my table model?

My object already knows about the table model. Instead of passing a reference to the table it self can i get the selected index using the model?

Upvotes: 5

Views: 11250

Answers (4)

John Zhang
John Zhang

Reputation: 1142

You can get the index from the bound Table and then you can use it to manipulate the table model. For example, if I want to delete a Row in my table model:

myTableModel.removeValueAt(myTable.getSelectedRow());

Upvotes: 0

Peter Štibraný
Peter Štibraný

Reputation: 32893

If you let your model class implement ListSelectionModel as well as TableModel, you will be able to get selection from one model... but you cannot extend two abstract model classes :-( (It also isn't very good idea anyway as your class will have too many responsibilities).

Upvotes: 0

willcodejavaforfood
willcodejavaforfood

Reputation: 44063

Like MrWiggles said you can get it from the ListSelectionModel which you is accessible from the table itself. However there are convenience methods in JTable to get the selected rows as well. If your table is sortable etc you will also need to go through the convertRowIndexToModel method :)

From the JTable JavaDoc:

   int[] selection = table.getSelectedRows();
   for (int i = 0; i < selection.length; i++) {
     selection[i] = table.convertRowIndexToModel(selection[i]);
   }
   // selection is now in terms of the underlying TableModel

Upvotes: 14

tddmonkey
tddmonkey

Reputation: 21184

The TableModel only concerns itself with the data, the ListSelectionModel concerns itself with what is currently selected, so, no you can't get the selected row from the TableModel.

Upvotes: 6

Related Questions