java实现树形菜单
时间: 2024-06-16 07:06:19 浏览: 73
关于树形菜单的实现 java
Java可以通过使用递归和面向对象的思想来实现树形菜单。面是一个简单的示例:
首先,我们需要定义一个树类,该类包含节点的值和子节点列表:
```java
class TreeNode {
private String value;
private List<TreeNode> children;
public TreeNode(String value) {
this.value = value;
this.children = new ArrayList<>();
}
public void addChild(TreeNode child) {
children.add(child);
}
public List<TreeNode> getChildren {
return children;
}
public String getValue() {
return value }
}
```
然后,我们可以创建一个树形菜单类,该类包含根节点和一些操作方法:
```java
class TreeMenu {
private TreeNode root;
public TreeMenu(TreeNode root) {
this.root = root;
}
public void printMenu() {
printNode(root, 0);
}
private void printNode(TreeNode node, int level) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < level; i++) {
sb.append(" "); // 每一层缩进两个空格
}
sb.append(node.getValue());
System.out.println(sb.toString());
List<TreeNode> children = node.getChildren();
for (TreeNode child : children) {
printNode(child, level + 1);
}
}
}
```
最后,我们可以使用上述类来创建树形菜单并打印出来:
```java
public class Main {
public static void main(String[] args) {
TreeNode root = new TreeNode("Root");
TreeNode node1 = new TreeNode("Node 1");
TreeNode node2 = new TreeNode("Node 2");
TreeNode node3 = new TreeNode("Node 3");
TreeNode node11 = new TreeNode("Node 1.1");
TreeNode node12 = new TreeNode("Node 1.2");
TreeNode node21 = new TreeNode("Node 2.1");
root.addChild(node1);
root.addChild(node2);
root.addChild(node3);
node1.addChild(node11);
node1.addChild(node12);
node2.addChild(node21);
TreeMenu treeMenu = new TreeMenu(root);
treeMenu.printMenu();
}
}
```
运行上述代码,将会输出以下树形菜单:
```
Root
Node 1
Node 1.1
Node 1.2
Node 2
Node 2.1
Node 3
```
阅读全文