如何将javafx TableView Size限制为必要的大小?

tho*_*inn 6 java listview javafx tableview tablecell

我正在编写一个简单的Questionare应用程序.我在自定义javaFX组件(代表一个问题)中使用TableView,它在ListView中用作ListCell(用于表示整个问卷).

我想要的是:每个ListCell使用尽可能少的空间(或必要的),同时仍然清除其全部内容.

会发生什么:TableView似乎默认为标准大小.如果表具有更多内容,则会在ScrollPane中显示其内容.如果TableView具有较少的内容,则它会填充空白空间.


我试图以多种方式解决我的问题:

  1. 最初我假设必须有一种方法停用滚动条.但我找不到任何办法.

  2. 然后我尝试通过更改PreferredSizeProperty来更改表的大小: table.setPrefHeight() 但是我找不到有关表有多大的任何信息. table.setPrefHeight(USE_COMPUTED_SIZE); 没有我希望的结果.

  3. 然后我尝试自己计算所需的高度,但我找不到任何方法来确定各行的高度.this.getTableRow().getHeight()在自定义TableCell的update方法中调用将导致NullPointerExceptions.当检查为null时,它仍将返回0! TableRow<T> tr = this.getTableRow(); if (tr != null) { System.out.println(tr.getHeight()); }

  4. 相当沮丧,我决定通过调用 table.setFixedCellSize(20); This严格限制自定义TableCells的点来修复行高, 否则我没有取得任何进展.但是,表高度也不等于行数乘以固定的行高,因为需要考虑表头.我无法访问表头或要求表头大小/高度.

你有什么建议我出错或者我忽略了什么来实现我的原始目标(拥有一个像显示每一行所需的那么大的ListCell,但不是一个空行吗?)任何帮助/我们非常欢迎您的想法!谢谢!

b3t*_*ing 1

使用绑定(示例有一个至少有 2 行的表视图,或者一个列表中所有项目的大小的表......

/**
 * Helper to set table height based on content 
 *
 * @param table        - the table in context
 * @param rowHeight    - the height of a single row, alternatively could use table.fixedCellSizeProperty()
 * @param headerHeight - the height of the table header
 * @param margin       - a value for the margins
 */
public void tableHeightHelper(TableView<?> table, int rowHeight, int headerHeight, int margin) {
    table.prefHeightProperty().bind(Bindings.max(2, Bindings.size(table.getItems()))
                                            .multiply(rowHeight)
                                            .add(headerHeight)
                                            .add(margin));
    table.minHeightProperty().bind(table.prefHeightProperty());
    table.maxHeightProperty().bind(table.prefHeightProperty());
}
Run Code Online (Sandbox Code Playgroud)

通过列表上的侦听器或订阅为表提供数据,表大小将始终根据项目进行调整

这实际上取决于您如何自定义列表视图的单元格,以及您如何配置单元格工厂...只要 ListView 中的fixedCellProperty() 未设置,我就没有遇到个人问题ListView 中的单元格会根据其包含的节点的大小进行调整。