在JavaFX TableView中显示Google Guava表的规范方式

时间:2016-04-06 17:19:31

标签: javafx tableview guava

是否有规范方法在JavaFX TableView中显示Google Guava表?我希望像

这样的东西
com.google.common.collect.Table guavaTable = ...;
javafx.scene.control.TableView<Object> tableView = ...;
tableView.setItems(new GuavaTableConverter(table));

但找不到像GuavaTableConverter这样的网页搜索内容。

1 个答案:

答案 0 :(得分:2)

自己这样做很容易。只需为columnKeySet()中的每个值创建一个列,为rowKeySet()中的每个值创建一个项目:

public final class GuavaTableConverter {

    private GuavaTableConverter() {
    }

    public static <R, C, V> List<TableColumn<R, String>> getColumns(Table<R, C, V> table, Function<C, String> headingConverter, Function<V, String> valueConverter) {
        Set<C> columns = table.columnKeySet();
        List<TableColumn<R, String>> result = new ArrayList<>(columns.size());
        for (C c : columns) {
            TableColumn<R, String> col = new TableColumn<>(headingConverter.apply(c));
            col.setCellValueFactory(cd -> Bindings.createStringBinding(() -> {
                V value = table.get(cd.getValue(), c);
                return value == null ? null : valueConverter.apply(value);
            }));
            result.add(col);
        }
        return result;
    }

    public static <R> TableColumn<R, String> getRowColumn(Table<R, ? , ?> table, String name, Function<R, String> converter) {
        TableColumn<R, String> column = new TableColumn<>(name);
        column.setCellValueFactory(c -> Bindings.createStringBinding(() -> converter.apply(c.getValue())));
        return column;
    }

    public static <R> ObservableList<R> getItems(Table<R, ?, ?> table) {
        return FXCollections.observableArrayList(table.rowKeySet());
    }
}

用法:

@Override
public void start(Stage primaryStage) {
    HashBasedTable<Integer, Integer, String> table = HashBasedTable.create();

    table.put(0, 0, "Hello World");
    table.put(2, 0, "A");
    table.put(2, 42, "B");

    TableView<Integer> tv = new TableView<>(GuavaTableConverter.getItems(table));
    tv.getColumns().add(GuavaTableConverter.getRowColumn(table, "row", Object::toString));
    tv.getColumns().addAll(GuavaTableConverter.getColumns(table, Object::toString, Object::toString));

    primaryStage.setScene(new Scene(tv));
    primaryStage.show();
}