开发者

JTable's and DefaultTableModel's row indexes lose their synchronization after I sort JTable

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开发者_JS百科 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?


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜