JavaFX - 将TableView高度调整为行数

Jus*_*guy 13 java javafx tableview

我希望我的TableView的高度适应填充的行数,因此它永远不会显示任何空行.换句话说,TableView的高度不应超出最后填充的行.我该怎么做呢?

eck*_*kig 16

如果你想要这个工作,你必须设置fixedCellSize.

然后,您可以将表的高度TableView与表中包含的项的大小绑定,再乘以固定的单元格大小.

演示:

@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();
}
Run Code Online (Sandbox Code Playgroud)

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

  • 嗯...对我不起作用(任意因素几乎肯定会迟早失败;) (5认同)