首页 > 解决方案 > JavaFX TreeView 的 TreeCell 全宽

问题描述

嗨stackoverflow社区,

我用 javafx 在 kotlin 中开发了一个应用程序。为此,我需要一个带有自定义 TreeCell 表示的 TreeView。我的问题是始终保留 TreeCell 内容(见下图)。我想要做的是,TreeCell 内容从左到右拉伸。(如 AnchorPane.leftAnchor = 0 和 AnchorPane.rightAnchor = 0)

fxml 看起来像这样:

<VBox prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/10.0.2-internal"
  xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.bli.bla.blu.conrollers.MyController">
  <TreeView fx:id="treeView" showRoot="false" VBox.vgrow="ALWAYS">
  </TreeView>
</VBox>

在我调用的控制器中:

treeView?.setCellFactory { PositionTreeCell() }

PositionTreeCell 是:

class PositionTreeCell : TreeCell<PositionEntryController>() {
override fun updateItem(item: PositionEntryController?, empty: Boolean) {
    super.updateItem(item, empty)
    if (empty || item == null) {
        text = null
        graphic = null
        contextMenu = null
    } else {
        text = null
        graphic = getPositionTreeCellGraphic(item)
        contextMenu = null
    }
}

private fun getPositionTreeCellGraphic(item: PositionEntryController): Node? {
    if (item is TypeA) {
        val loader = FXMLLoader()
        loader.resources = ResourceBundle.getBundle("Resources", Locale.getDefault())
        loader.setControllerFactory {
            item
        }
        val parent = loader.load<Parent>(javaClass.getResourceAsStream("/fxml/typeA.fxml"))
        return parent
    } else if (item is TypeB)
        return TODO()
    else
        return null
}
}

fxml中的自定义模板是:

<GridPane gridLinesVisible="true" prefHeight="20.0" prefWidth="800" xmlns="http://javafx.com/javafx/10.0.2-internal"
      xmlns:fx="http://javafx.com/fxml/1"
      fx:controller="de.bli.bla.blu.conrollers.PositionDefinitionController">
<Label fx:id="keyLabel"/>
<Label fx:id="positionNameLabel" GridPane.columnIndex="1"/>
<Label fx:id="piecePriceLabel" GridPane.columnIndex="2"/>
<Label fx:id="unitLabel" GridPane.columnIndex="3"/>

<columnConstraints>
    <ColumnConstraints maxWidth="100"/>
    <ColumnConstraints/>
    <ColumnConstraints maxWidth="100"/>
    <ColumnConstraints maxWidth="50"/>
</columnConstraints>
<rowConstraints>
    <RowConstraints/>
</rowConstraints>
</GridPane>

它看起来像什么:

在此处输入图像描述

我尝试的是在 PositionTreeCell 中设置 AnchorPane,但这不起作用。有谁知道如何做到这一点?

标签: kotlinjavafxtreeview

解决方案


推荐阅读