gpt4 book ai didi

javafx - 迭代 TreeView 节点

转载 作者:行者123 更新时间:2023-12-02 04:24:04 25 4
gpt4 key购买 nike

我正在使用此代码迭代所有 TreeView 节点。

for (TreeItem<DynamicTreeNodeModel> children1 : children)
{
ObservableList<TreeItem<DynamicTreeNodeModel>> children2 = children1.getChildren();

for (TreeItem<DynamicTreeNodeModel> children3 : children2)
{
ObservableList<TreeItem<DynamicTreeNodeModel>> children4 = children3.getChildren();

TreeItem<DynamicTreeNodeModel> tempValue = null;

for (TreeItem<DynamicTreeNodeModel> children5 : children4)
{
// some logic
}
}
}

有没有更好的方法来访问 TreeView 的低级节点?

最佳答案

您可以只使用递归方法,检查当前节点是否有子节点。如果有,它会再次调用相同的方法,否则它会打印该节点。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class IterateTree extends Application {


public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Tree View Sample");

TreeItem<String> rootItem = new TreeItem<String> ("Inbox");
rootItem.setExpanded(true);
for (int i = 1; i < 5; i++) {
rootItem.getChildren().add(createTreeItem(i));
}
TreeView<String> tree = new TreeView<String> (rootItem);
StackPane root = new StackPane();
root.getChildren().add(tree);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
// print children
printChildren(rootItem);
}

private TreeItem<String> createTreeItem(int num) {
TreeItem<String> rootItem = new TreeItem<String> ("Group " + num);
for (int i = 1; i < 6; i++) {
TreeItem<String> item = new TreeItem<String> ("Message" + i);
rootItem.getChildren().add(item);
}
return rootItem;
}

private void printChildren(TreeItem<String> root){
System.out.println("Current Parent :" + root.getValue());
for(TreeItem<String> child: root.getChildren()){
if(child.getChildren().isEmpty()){
System.out.println(child.getValue());
} else {
printChildren(child);
}
}
}
}

关于javafx - 迭代 TreeView 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28342309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com