Why is my TableColumn.setSortable() showing the sort graphic on the table header when I double-click on it, but it is not actually doing any sort at all? I would imagine it naturally knows how to sort Numbers? Do I have to set an explicit comparator even for types that have a natural sort behavior?
public class PenaltyDashboardManager {
private final TableView<Penalty> penaltyTable = new TableView<Penalty>();
/* ... */
private void initializeTable() {
penaltyTable.setItems(Penalty.getPenaltyManager().getPenalties());
penaltyTable.setEditable(true);
TableColumn<Penalty,Number> penaltyId = new TableColumn<>("ID");
penaltyId.setCellValueFactory(c -> c.getValue().getPenaltyIdProperty());
penaltyId.setEditable(true);
penaltyId.setSortable(true);
/* ... */
penaltyTable.getColumns.add(penaltyId);
}
}
UPDATE
Very odd. I tried to create a simple example to demonstate the sorting not working. But this simple column of integers is sorting just fine :/
public final class TableSortTest extends Application {
private static final ObservableList<NumericCombo> values = FXCollections.observableList(
IntStream.range(1, 100).mapToObj(i -> new NumericCombo()).collect(Collectors.toList()));
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Collections.shuffle(values);
TableView<NumericCombo> tableView = new TableView<>();
tableView.setItems(values);
TableColumn<NumericCombo,Number> combo1 = new TableColumn<>("COMBO 1");
combo1.setCellValueFactory(c -> new ReadOnlyObjectWrapper<>(c.getValue().combo1));
TableColumn<NumericCombo,Number> combo2 = new TableColumn<>("COMBO 2");
combo2.setCellValueFactory(c -> c.getValue().combo2);
TableColumn<NumericCombo,Number> combo3 = new TableColumn<>("COMBO 3");
combo3.setCellValueFactory(c -> c.getValue().combo3);
tableView.getColumns().addAll(combo1,combo2,combo3);
Group root = new Group(tableView);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
private static final class NumericCombo {
private static final Random rand = new Random();
private final int combo1;
private final IntegerProperty combo2;
private final IntegerProperty combo3;
private NumericCombo() {
combo1 = rand.nextInt((10000 - 0) + 1);
combo2 = new SimpleIntegerProperty(rand.nextInt((10000 - 0) + 1));
combo3 = new SimpleIntegerProperty(rand.nextInt((10000 - 0) + 1));
}
}
}
I found the issue! I was using my own implementation of ObservableList, called ObservableImmutableList. It wraps the ObservableList interface around a Guava ImmutableList. Since the ImmutableList is not modifiable, it cannot be sorted... even in a TableView.
This transitions to another issue I'm struggling to figure out. How do I sort my
ObservableImmutableList
? So I posted another question.