views:

282

answers:

2

JAVA NETBEANS

// resultsTable, myModel

JTable resultsTable;

DefaultTableModel myModel; //javax.swing.table.DefaultTableModel

myModel = (DefaultTableModel) resultsTable.getModel();

// event of clicking on item of table

String value = (String) myModel.getValueAt(resultsTable.getSelectedRow(), columnIndex)

I use JTable and DefaultTableModel to view a table of various info and I want to get a value of a certain column of the selected index of the table.

The code I wrote above works fine except when: I use the sort of the GUI (click on the field name I want to sort on the table) The table is properly sorted but after that when I select a row, it gets the value of the row that was there before the sort. This means that after sorting (using the JTable's GUI) the 'myModel' and 'resultsTable' objects have different row indexes.

How do I synchronize those two?

+1  A: 

You need to use the 'convertXXX' methods on the JTable see the JavaDoc

int row = resultsTable.getSelectedRow();
if (row != -1) {
   row = table.convertRowIndexToModel(row);
   String value = (String) myModel.getValueAt(, columnIndex)
Guillaume
Thanks very usefull
Stefanos Kargas
A: 

Except from the solution Guillaume gave (Thanks) I did this:

// resultsTable, myModel

JTable resultsTable;

DefaultTableModel myModel; //javax.swing.table.DefaultTableModel

myModel = (DefaultTableModel) resultsTable.getModel();

// event of clicking on item of table

String value = (String) resultsTable.getValueAt(resultsTable.getSelectedRow(), columnIndex)

I used the resultsTable Object instead of the myModel Object to get the value.

Stefanos Kargas