我想在TitlePana中添加几个TreeView。
private static TitledPane pane = new TitledPane("Connections", null);
public static void initTree(String name)
{
pane.setContent(tree(name));
}
pane.setContent(<node>);
但是当我添加TreeView时,新节点总是替换旧节点。这是一个设计问题。任何想法都是代码问题吗?
答案 0 :(得分:3)
将标题窗格的内容设置为某个布局窗格,然后将树视图添加到布局窗格。
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TitledPane;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TreesInATitledPane extends Application {
@Override
public void start(Stage primaryStage) {
final TitledPane titledPane = new TitledPane();
titledPane.setText("Trees");
final VBox forest = new VBox(5);
final int NUM_TREES = 4 ;
for (int i=1; i<= NUM_TREES; i++) {
forest.getChildren().add(createRandomTree("Tree "+i));
}
titledPane.setContent(forest);
final BorderPane root = new BorderPane();
root.setTop(titledPane);
final Scene scene = new Scene(root, 300, 600);
primaryStage.setTitle("Can't see the forest for the trees");
primaryStage.setScene(scene);
primaryStage.show();
}
public TreeView<String> createRandomTree(String prefix) {
final Random rng = new Random();
List<TreeItem<String>> nodes = new ArrayList<>();
TreeItem<String> root = new TreeItem<>(prefix + " Root");
root.setExpanded(true);
nodes.add(root);
for (int i=1 ; i < 15; i++) {
final TreeItem<String> treeItem = new TreeItem<>(prefix + " Item "+i);
treeItem.setExpanded(true);
nodes.get(rng.nextInt(i)).getChildren().add(treeItem);
nodes.add(treeItem);
}
TreeView<String> tree = new TreeView<>(root);
return tree ;
}
public static void main(String[] args) {
launch(args);
}
}