Claus
Claus

Reputation: 2304

How to prevent user from changing sort order of JavaFX Table?

I have a JavaFX table with a default sort specified via FXML

<TableView>
  <columns>
    ...
  </columns>
  <sortOrder>
    ...
  </sortOrder>
</TableView>

Whenever I add a row I resort the table, which does exactly what I want.

myTable.getItems().add(...)
myTable.sort()

Now, however, I want to prevent the user from changing the sort order. How can I do that?

I tried using the <TableColumn sortable="false" .../> attribute but if specified on the columns I want to sort by then these columns are no longer sorted.

Upvotes: 0

Views: 92

Answers (1)

Claus
Claus

Reputation: 2304

Slaw's suggestion to use the SortedList works quite nicely. Here's what needs to be done:

@FXML
private TableView<MyThing> tableView;
private ObservableList<MyThing> observableList = FXCollections.observableArrayList();

@Override
public void initialize(URL location, ResourceBundle resources) {
    SortedList<MyThing> sortedList = observableList.sorted(Comparator.comparing(MyThing::getDate).thenComparing(MyThing::getTime));
    tableView.setItems(sortedList);
    
public void onAdd(MyThing myThing) {
    observableList.add(myThing);        

Then just use <TableColumn sortable="false" .../> on all columns to prevent the user from changing the sort order.

Upvotes: 1

Related Questions