JavaFX - Adapt TableView height to number of rows

前端 未结 1 708
逝去的感伤
逝去的感伤 2020-12-06 05:00

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

相关标签:
1条回答
  • 2020-12-06 05:43

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

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

    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.

    0 讨论(0)
提交回复
热议问题