JavaFX TableView有两个固定列,最后一个占用可用空间 [英] JavaFX TableView with two fixed-columns and last one taking available space
问题描述
我正在尝试制作一个简单的3列TableView:
I'm trying to make a simple 3-column TableView:
- 包含固定大小图标的一个图标列。此列不得调整大小,并且必须具有固定大小。
- 一个具有预定义首选大小的文本列,如果需要可以调整大小。
- 最后一列占用了所有可用空间。
不幸的是,这个简单的用例在Java FX 8中看起来非常复杂。尝试了以下内容,根据我对文档的理解,它应该有效:
Unfortunatly, this simple use case seems to be really complicated with Java FX 8. I tried the following, which should work according to my understanding of the documentation:
TableColumn<DebuggerItem, ImageView> iconColumn = new TableColumn<>("ICON");
TableColumn<DebuggerItem, String> typeColumn = new TableColumn<>("TEXT");
TableColumn<DebuggerItem, String> textColumn = new TableColumn<>("DATA");
setColumnResizePolicy(CONSTRAINED_RESIZE_POLICY);
// Fixed size column
iconColumn.setPrefWidth(40);
iconColumn.setMinWidth(40);
iconColumn.setMaxWidth(40);
iconColumn.setResizable(false);
// Predefined preferred size of 100px
typeColumn.setPrefWidth(100);
getColumns().addAll(iconColumn, typeColumn, textColumn);
这导致以下TableView:
This results in the following TableView:
我们可以看到,如果第一列的大小正确,则第二列和第三列具有相同的大小,这不是我的预期。第二列应该是100px宽,最后一列占据剩下的空间。
We can see that if the first column has a correct size, the second and the hird have the same size, which is not what I expected. The second column should be 100px wide, and the last one take the rest of the space.
我错过了什么?
推荐答案
根据@kleopatra链接,解决方案是使用属性来计算最后一列宽度,而不是使用 CONSTRAINED_RESIZE_POLICY
:
According to @kleopatra link, the solution is to use properties to compute last column width, and NOT use CONSTRAINED_RESIZE_POLICY
:
LastColumnWidth = TableViewWidth - SUM(Other Columns Widths)
根据我的示例,给出以下Java代码:
Which, according to my example give the following Java code:
TableColumn<DebuggerItem, ImageView> iconColumn = new TableColumn<>("ICON");
TableColumn<DebuggerItem, String> typeColumn = new TableColumn<>("TEXT");
TableColumn<DebuggerItem, String> textColumn = new TableColumn<>("DATA");
// Fixed size column
iconColumn.setPrefWidth(40);
iconColumn.setMinWidth(40);
iconColumn.setMaxWidth(40);
iconColumn.setResizable(false);
// Predefined preferred size of 100px
typeColumn.setPrefWidth(100);
// Automatic width for last column
textColumn.prefWidthProperty().bind(
widthProperty().subtract(
iconColumn.widthProperty()).subtract(
typeColumn.widthProperty()).subtract(2)
);
getColumns().addAll(iconColumn, typeColumn, textColumn);
请注意,我们需要减去2个像素才能得到确切的宽度,不清楚原因。
Please note that we need to substract 2 pixels to get the exact width, it's not clear why.
这篇关于JavaFX TableView有两个固定列,最后一个占用可用空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!