java构建树形菜单代码
时间: 2023-05-24 12:01:42 浏览: 56
Sure, I can help you with that. Here is a sample code for constructing a tree menu in Java:
public class Node {
private String label;
private List<Node> children;
public Node(String label) {
this.label = label;
this.children = new ArrayList<>();
}
public String getLabel() {
return label;
}
public List<Node> getChildren() {
return children;
}
public void addChild(Node node) {
children.add(node);
}
}
public class Tree {
private Node root;
public Tree(Node root) {
this.root = root;
}
public void printTree() {
printTree(root, 0);
}
private void printTree(Node node, int depth) {
String prefix = "";
for (int i = 0; i < depth; i++) {
prefix += " ";
}
System.out.println(prefix + node.getLabel());
for (Node child : node.getChildren()) {
printTree(child, depth + 1);
}
}
}
To use this code, you can create a new Node for each item in your tree and add them as children to other nodes as needed. Finally, you can create a Tree instance with the root node and call its printTree() method to display the tree.