Question

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?

Was it helpful?

Solution

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(row, columnIndex)

OTHER TIPS

A problem with using the JTable.getValueAt() is to get the column you want. When the columns are moved around in the GUI the indexes "change" to match the view. By using the AbstractTableModel.getValueAt() and the JTable.convertXXX() (as outlined by Guillaume) it's just a matter of using the column indexes for the model when retrieving data.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top