Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JTable, TableRowSorter and custom TableCellRenderer

843806Jul 20 2008 — edited Jul 20 2008
Hello!

Successfully added the TableRowSorter to a JTable (MyTable) which is using MyTableModel (extending AbstractTableModel). I want certain cells to be colored yellow. This works when no sorting is applied, but the coloring doesn't change when hitting the JTableHeader and the same cells (same row, col) are still yellow and not where the certain values (e.g. "test") are residing now.
public class MyTable extends JTable {

    private String cellContent;
    private Object obj;
    private MyTableModel _myTableModel;
    
    public MyTable(MyTableModel myTableModel) {
        super(myTableModel);
        _myTableModel = myTableModel;
    }
    
    public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
        Component c = super.prepareRenderer(renderer, row, col);
        
        // Set beckground colors in cell according to their content.
        obj = _myTableModel.getValueAt(row, col);
        cellContent = (obj != null) ? obj.toString() : "";
        if (this.isCellSelected(row, col)) {
            // nothing to do.
        } else if (col == 2 && cellContent.equals("test")) {
            c.setBackground(new Color(255, 255, 220));
        } else {
            c.setBackground(this.getBackground());
        }
        return c;
    }
}
Table configured similarily like this:
            MyTable _table = new MyTable(new MyTableModel());
            _table.setRowSorter(new TableRowSorter<TableModel>(_table.getModel()));
            ArrayList<RowSorter.SortKey> _sortKeys = new ArrayList<RowSorter.SortKey>();
            _sortKeys.add(new RowSorter.SortKey(2, SortOrder.ASCENDING));
            _sortKeys.add(new RowSorter.SortKey(3, SortOrder.ASCENDING));
            _table.getRowSorter().setSortKeys(_sortKeys);
Any ideas how to achieve that the Renderer is updating also when the sort order is changed?

Thanks in advance!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 17 2008
Added on Jul 20 2008
2 comments
117 views