开发者

Sorting with a custom AbstractTableModel

I've made my own class which extends AbstractTableModel. The idea is to be able to store a hidden "id" collumn. The following code works well for this purpose:

public class GuiTa开发者_如何学运维bleModel extends AbstractTableModel {


List<Object[]> rowlist = new ArrayList<Object[]>();
List<String> colNames = new ArrayList<String>();

public void addRow(Object[] data) {
    rowlist.add(data);
}
public void addColumn(String name) {
    colNames.add(name);
}

public int getColumnCount() { 
    return colNames.size();
}

public int getRowCount() { 
    return rowlist.size();
}

public Object getValueAt(int row, int col) {
   return rowlist.get(row)[col];
}

@Override
public String getColumnName(int column) {
    return colNames.get(column);
}

@Override
public boolean isCellEditable(int rowIndex, int mColIndex) {
    return false;
}

As you can see above, its a very simple implementation. The problem is though, when someone sorts by column by clicking the column title in the JTable, the lists in the AbstractTableModel don't get updated. I need the lists to be in sync with the visual layout.

Any ideas on how I can do this?

Many Thanks


The problem is though, when someone sorts by column by clicking the column title in the JTable, the lists in the AbstractTableModel don't get updated

And that is exactly the way it should work. The data in the model should never change when you do a sort or reorder columns. Its only the view that changes.

If you want to get data from the table then you should be using:

table.getValueAt(row, column) 

and it will get you the proper value. If you need to get data from the model directly then you need to use:

table.getModel().getValueAt(table.convertRowIndexToModel(row), column);

The idea is to be able to store a hidden "id" collumn.

There is no reason to create a custom model for this. Just store all the data in the DefaultTableModel. Then you can remove the "ID" column from the view of the table.

table.getColumnModel().removeColumn( table.getColumn("ID") );

In this case the data in not in the view so you can't use table.getValueAt(...). Instead you must use table.getModel().getValueAt(...);


I think you are looking for JTable.convertRowIndexToModel as outlined at JTable's and DefaultTableModel's row indexes lose their synchronization after I sort JTable

Also, for more complicated sorting and filtering, try http://publicobject.com/glazedlists/


in my opinion, а good solution of your problem is the observer pattern http://en.wikipedia.org/wiki/Observer_pattern

your class has to implement observer interface to keep track of events that user generate by clicking on column title


Why not using JXTable ? You can find it here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜