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

问题描述 投票:1回答:1

如果已经提出这个问题,我很抱歉,但我的搜索失败了。

给定两个在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将根据该列的标准进行排序。

java sorting javafx tableview tablecolumn
1个回答
1
投票

为此,您需要绑定表列的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);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.