java JavaFX - 使 TableView 高度适应行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27945817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:41:05  来源:igfitidea点击:

JavaFX - Adapt TableView height to number of rows

javajavafxtableview

提问by Just some guy

I want my TableView's height to adapt to the number of filled rows, so that it never shows any empty rows. In other words, the height of the TableView should not go beyond the last filled row. How do I do this?

我希望我的 TableView 的高度适应填充的行数,这样它就不会显示任何空行。换句话说,TableView 的高度不应超过最后填充的行。我该怎么做呢?

回答by eckig

If you want this to work you have to set the fixedCellSize.

如果你想让它工作,你必须设置fixedCellSize.

Then you can bind the height of the TableViewto the size of the items contained in the table multiplied by the fixed cell size.

然后您可以将 的高度绑定TableView到表格中包含的项目的大小乘以固定单元格大小。

Demo:

演示:

@Override
public void start(Stage primaryStage) {

    TableView<String> tableView = new TableView<>();
    TableColumn<String, String> col1 = new TableColumn<>();
    col1.setCellValueFactory(cb -> new SimpleStringProperty(cb.getValue()));
    tableView.getColumns().add(col1);
    IntStream.range(0, 20).mapToObj(Integer::toString).forEach(tableView.getItems()::add);

    tableView.setFixedCellSize(25);
    tableView.prefHeightProperty().bind(tableView.fixedCellSizeProperty().multiply(Bindings.size(tableView.getItems()).add(1.01)));
    tableView.minHeightProperty().bind(tableView.prefHeightProperty());
    tableView.maxHeightProperty().bind(tableView.prefHeightProperty());

    BorderPane root = new BorderPane(tableView);
    root.setPadding(new Insets(10));
    Scene scene = new Scene(root, 400, 400);
    primaryStage.setScene(scene);
    primaryStage.show();
}

Note: I multiplied fixedCellSize * (data size + 1.01) to include the header row.

注意:我乘以 fixedCellSize *(数据大小 + 1.01)以包含标题行。