如何在 Java 中展开 JTree 行以显示所有节点和子节点


要展开 JTree 行以显示所有节点和子节点,请在 Java 中使用 expandRow() 方法。首先,创建一个节点 −

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 tree = new JTree(node);

使用 expandRow() 方法,并将其循环到行计数 −

for (int i = 0; i < tree.getRowCount(); i++) {
   tree.expandRow(i);
}

以下是展开 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);
      for (int i = 0; i < tree.getRowCount(); i++) {
         tree.expandRow(i);
      }
      tree.putClientProperty("JTree.lineStyle", "Angled");
      frame.add(tree);
      frame.setSize(550,400);
      frame.setVisible(true);
      frame.setLocationRelativeTo(null);
   }
}

输出

更新于:2019 年 7 月 30 日

713 次查看

开启你的 职业生涯

通过完成课程获得认证

开始
广告