在 JavaFX 中的两个 TableView 之间绑定 TableColumns 的排序行为



如果已经问过这个问题,我很抱歉,但我的搜索没有成功。

给定两个在 JavaFX 中具有相同列数和类型的表,例如:

// First Table
private TableView table1 = new TableView();
TableColumn col11 = new TableColumn("col1");
TableColumn col12 = new TableColumn("col2");
table1.getColumns().addAll(col11, col12);

// Second Table
private TableView table2 = new TableView();
TableColumn col21 = new TableColumn("col1");
TableColumn col22 = new TableColumn("col2");
table2.getColumns().addAll(col21, col22);
[... logic adding and showing tables here ...]

如何绑定col11col21之间的排序属性以及col21col22,以便当我单击table1列的标题(显示排序箭头(时,table2将根据该列的条件进行排序。

为此,

您需要绑定表列的sortType属性,并确保表的sortOrder包含相应的列:

/**
  * holder for boolean variable to be passed as reference
  */
private static class BoolContainer {
    boolean value;
}
public static <T> void createSortBinding(TableView<T> table1, TableView<T> table2) {
    final int count = table1.getColumns().size();
    if (table2.getColumns().size() != count) {
        throw new IllegalArgumentException();
    }
    // bind sort types
    for (int i = 0; i < count; i++) {
        table1.getColumns().get(i).sortTypeProperty().bindBidirectional(
                table2.getColumns().get(i).sortTypeProperty());
    }
    BoolContainer container = new BoolContainer();
    bindList(table1, table2, container);
    bindList(table2, table1, container);
}
/**
  * helper for one direction of the binding of the source orders
  */
private static <T> void bindList(TableView<T> table1,
        TableView<T> table2,
        BoolContainer modifyingHolder) {
    ObservableList<TableColumn<T, ?>> sourceColumns = table1.getColumns();
    ObservableList<TableColumn<T, ?>> sourceSortOrder = table1.getSortOrder();
    ObservableList<TableColumn<T, ?>> targetColumns = table2.getColumns();
    ObservableList<TableColumn<T, ?>> targetSortOrder = table2.getSortOrder();
    // create map to make sort order independent form column order
    Map<TableColumn<T, ?>, TableColumn<T, ?>> map = new HashMap<>();
    for (int i = 0, size = sourceColumns.size(); i < size; i++) {
        map.put(sourceColumns.get(i), targetColumns.get(i));
    }
    sourceSortOrder.addListener((Observable o) -> {
        if (!modifyingHolder.value) {
            modifyingHolder.value = true;
            // use map to get corresponding sort order of other table
            final int size = sourceSortOrder.size();
            TableColumn<T, ?>[] sortOrder = new TableColumn[size];
            for (int i = 0; i< size; i++) {
                sortOrder[i] = map.get(sourceSortOrder.get(i));
            }
            targetSortOrder.setAll(sortOrder);
            modifyingHolder.value = false;
        }
    });
}

用法:

createSortBinding(table1, table2);

最新更新