我尝试在JavaFX App中实现TreeView。但不幸的是没有展示任何物品,但我找不到问题。我搜索了一些例子,就像他们一样。
我将TreeView控件放到SceneBuilder中的FXML文件中,并选择生成的ControllerClass,并从此类中选择Treeview字段作为SceneBuilder中TreeView控件的id。
我检查了question,其中错误是分配了TreeView
的新实例,但这不是我的问题,因为我直接设置了root。
那是我的控制器代码:
public class FXMLDocumentController implements Initializable {
@FXML
private Label label;
@FXML
private TreeView<String> treeView;
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
TreeItem<String> root = new TreeItem<>("root");
for (int i = 0; i < 10; i++) {
TreeItem<String> child = new TreeItem<>("Children " + i);
root.getChildren().add(child);
}
root.setExpanded(true);
treeView.setRoot(root);// = new TreeView<String> (rootItem);
treeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
}
}
我的FXML代码:
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1">
<children>
<SplitPane dividerPositions="0.29797979797979796" layoutX="134.0" layoutY="154.0" prefHeight="600.0" prefWidth="800.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<TreeView fx:id="treeView" layoutX="39.0" layoutY="61.0" prefHeight="598.0" prefWidth="235.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
</items>
</SplitPane>
</children>
</AnchorPane>