TableView: adjust number of visible rows

前端 未结 6 546
梦谈多话
梦谈多话 2020-11-29 06:30

I\'m using this table to display data in Table View:

import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans         


        
6条回答
  •  情深已故
    2020-11-29 07:24

    If you're not wedded to bindings, a simple way to do this is to calculate the desired height based on the fixed cell size (cf. Fred Danna's answer) and update it with a listener on the table data.

    static void setTableHeightByRowCount(TableView table, ObservableList data) {
      int rowCount = data.size();
      TableHeaderRow headerRow = (TableHeaderRow) table.lookup("TableHeaderRow");
      double tableHeight = (rowCount * table.getFixedCellSize())
        // add the insets or we'll be short by a few pixels
        + table.getInsets().getTop() + table.getInsets().getBottom()
        // header row has its own (different) height
        + (headerRow == null ? 0 : headerRow.getHeight())
        ;
    
      table.setMinHeight(tableHeight);
      table.setMaxHeight(tableHeight);
      table.setPrefHeight(tableHeight);
    }
    

    In start(Stage), we create the table and add a ListChangeListener:

    TableView table = new TableView<>();
    table.setFixedCellSize(24);
    table.getItems().addListener((ListChangeListener) c ->
      setTableHeightByRowCount(table, c.getList()));
    
    // init scene etc...
    
    stage.show();
    table.getItems().addAll("Stacey", "Kristy", "Mary Anne", "Claudia");
    

    Note that the table header row doesn't exist till after stage.show(), so the simplest thing to do is to wait to set the table data till then. Alternatively, we could set the data at table construction time, and then call setTableHeightByRowCount() explicitly:

    TableView table = new TableView<>(
      FXCollections.observableArrayList("Stacey", "Kristy", "Mary Anne", "Claudia")
    );
    
    // add listener, init scene etc...
    
    stage.show();
    setTableHeightByRowCount(table, table.getItems());
    

提交回复
热议问题