Archive

Posts Tagged ‘sort’

Recipe 6: Sort an OutlineView programmatically

November 27, 2011 Leave a comment

Problem

How can I sort a column of an OutlineView programmatically?

Solution

You can click on the header of a column in an OutlineView to sort it in ascending/descending order. But how can you do this programmatically? E.g. when you click on a button you wish to have the outline view sorted by one column, and when you click another button to have it sorted based on another column:

/**
 * Sort the outline view {@code ov} on the given {@code field}.
 * @param ov outline view to sort
 * @param field to sort upon
 * @param ascending if {@code true} then the list is sorted in ascending order, if {@code false} in descending order.
 */
public static void sortBy(final OutlineView ov, final String field, final boolean ascending) {
  ETableColumnModel columnModel = (ETableColumnModel) ov.getOutline().getColumnModel();
  int columnCount = columnModel.getColumnCount();
  columnModel.clearSortedColumns();
  for (int i = 0; i < columnCount; i++) {
    ETableColumn column = (ETableColumn)columnModel.getColumn(i);
    if (column.getHeaderValue().equals(field)) {
      columnModel.setColumnSorted(column, ascending, 1);
    }
  }
  TableModel model = ov.getOutline().getModel();
  ov.getOutline().tableChanged(new TableModelEvent(model, 0, model.getRowCount()));
}
Categories: OutlineView Tags: ,