如何在 Java 中显示树形结构的数据?


要显示树形结构的数据,请在 Java Swing 中使用 JTree 控件。

首先,在树中创建一个节点 -

DefaultMutableTreeNode node = new DefaultMutableTreeNode("Project");

现在,向上面创建的节点添加节点 -

DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("App");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Website");
DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("WebApp");
node.add(node1);
node.add(node2);
node.add(node3);

现在,创建更多节点并将其设置为我们上面创建的节点的子节点 -

DefaultMutableTreeNode one = new DefaultMutableTreeNode("Learning website");
DefaultMutableTreeNode two = new DefaultMutableTreeNode("Business website");
DefaultMutableTreeNode three = new DefaultMutableTreeNode("News publishing website");
DefaultMutableTreeNode four = new DefaultMutableTreeNode("Android app");
DefaultMutableTreeNode five = new DefaultMutableTreeNode("iOS app");
DefaultMutableTreeNode six = new DefaultMutableTreeNode("Editor WebApp");
node1.add(one);
node1.add(two);
node1.add(three);
node2.add(four);
node2.add(five);
node3.add(six);

现在,创建一个 JTree 并在此 JTree 中设置根节点 -

JTree tree = new JTree(node);

以下是使用 Java Swing JTree 显示树形结构数据的示例 -

示例

package my;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      DefaultMutableTreeNode node = new DefaultMutableTreeNode("Project");
      DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("App");
      DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Website");
      DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("WebApp");
      node.add(node1);
      node.add(node2);
      node.add(node3);
      DefaultMutableTreeNode one = new DefaultMutableTreeNode("Learning website");
      DefaultMutableTreeNode two = new DefaultMutableTreeNode("Business website");
      DefaultMutableTreeNode three = new DefaultMutableTreeNode("News publishing website");
      DefaultMutableTreeNode four = new DefaultMutableTreeNode("Android app");
      DefaultMutableTreeNode five = new DefaultMutableTreeNode("iOS app");
      DefaultMutableTreeNode six = new DefaultMutableTreeNode("Editor WebApp");
      node1.add(one);
      node1.add(two);
      node1.add(three);
      node2.add(four);
      node2.add(five);
      node3.add(six);
      JTree tree = new JTree(node);
      frame.add(tree);
      frame.setSize(550,400);
      frame.setVisible(true);
   }
}

输出

更新于: 2019 年 7 月 30 日

726 次浏览

开启您的 事业

完成课程即可获得认证

开始
广告