注:這個回答假設「改變ObservableList的財產」,其實應改爲「ObservableList的項目的屬性更改」。它的假設是不正確的,我會刪除。
SortedList是清理解決方案,用於TableView中的可排序數據 - 它的設計和實現是爲了在包裹列表發生更改時保持自身排序。如果提供,支持列表會通知其聽衆有關更改。這是工作無需額外的客戶端代碼修改列表(如添加/刪除/項目集)。另一方面,它沒有通用的方法可以知道所包含項目屬性的修改:客戶端代碼必須提供一個提取器(aka回調函數,返回一個Observables數組),它允許列表激發更新事件給聽衆。
一個例子(人演示豆具有明顯的性能 - 與你最喜歡的例子豆代替),編輯按鈕只是一個前加「Z」被選擇的人的姓氏。
public class TableViewSortSample extends Application {
private Parent getContent() {
// wrap the backing list into an observableList with an extractor
ObservableList<Person> persons = FXCollections.observableList(
Person.persons(),
person -> new Observable[] {person.lastNameProperty(), person.firstNameProperty()}
);
// wrap the observableList into a sortedList
SortedList<Person> sortedPersons = new SortedList<>(persons);
// set the sorted list as items to a tableView
TableView<Person> table = new TableView<>(sortedPersons);
// bind the comparator of the sorted list to the table's comparator
sortedPersons.comparatorProperty().bind(table.comparatorProperty());
TableColumn<Person, String> firstName = new TableColumn<>("First Name");
firstName.setCellValueFactory(new PropertyValueFactory<>("firstName"));
TableColumn<Person, String> lastName = new TableColumn<>("Last Name");
lastName.setCellValueFactory(new PropertyValueFactory<>("lastName"));
table.getColumns().addAll(firstName, lastName);
Button edit = new Button("Edit");
edit.setOnAction(e -> {
Person person = table.getSelectionModel().getSelectedItem();
if (person != null) {
person.setLastName("z" + person.getLastName());
}
});
VBox pane = new VBox(table, edit);
return pane;
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(getContent()));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
「* TableView的比較器綁定到SortedList *」=>的比較器而不是相反的。你有使用排序列表的原因嗎?我希望當項目列表發生變異(添加/刪除)時,對錶格視圖的排序進行「刷新」,但是當項目本身發生變化時,不會進行排序。因此,您可能需要在複選框上添加一個偵聽器並以編程方式重新對錶進行排序。 – assylias
我使用SortedList主要是因爲它是新的,並認爲它會更有效的排序。但排序列表不能手動排序(可能有一個變通方法),所以我切換到顯示ObservableList和它的作品(我不得不在每次更改呼叫FXCollections.sort()) –
其實,我也必須得到的比較爲.compareTo()函數手動創建TableView,但它現在可用! –