Search code examples
javaswingjtabletablesorter

How to sort rows based on a column added dynamically in jtable?


There already exist a jtable, and I need to add a column dynamically, then set table cell renderer for that column, the cell renderer is jlabel with icon. I already finished that.

My question is : Right now I need to sort that column based on different icons used in table cell renderer, so how to do that? Thank you.

There are the related code:

    JTable table;// the table is already existed, I cannot change it

    TableColumn column = new TableColumn();

    column.setHeaderValue("Icon");
    column.setCellRenderer(new IconCellRenderer());

    table.addColumn(column);


public class IconCellRenderer extends DefaultTableCellRenderer
{
  private static final long serialVersionUID = 1L;

  public IconCellRenderer()
  {
    super();
  }

  @Override
  public Component getTableCellRendererComponent(JTable pTable, Object pValue,
      boolean pIsSelected, boolean pHasFocus, int pRow, int pColumn)
  {
    JLabel label = new JLabel();


    if (checkCondition(..))
    {
      label.setIcon(iconOne);
    } 
    else
    {
      label.setIcon(iconTwo));
    }

    label.setHorizontalAlignment(SwingConstants.CENTER);

    return label;
  }

}

Solution

  • For that purposes you can use TableRowSorter, and set Comparator to needed column. In that comparator you can compare values of cells and sorting them:

    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    sorter.setComparator(0, new Comparator<Object>() {
    
        @Override
        public int compare(Object o1, Object o2) {
            return 0;
        }
    });
    table.setRowSorter(sorter);
    

    table is your JTable , model is model of your table.

    read more about sorting in JTable.