如何在 Java 中获取 JTree 组件中此节点之后的叶子?


使用 getNextLeaf() 方法来获取 JTree 中此节点之后的叶子。此处,我们在控制台(Console)中显示节点“three”之后的叶子 −

System.out.println("Next leaf after this node = "+three.getNextLeaf());

以下示例说明了如何获取 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("Products");
      DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Clothing (Product1 - P66778)");
      DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Accessories (Product2 - P66779)");
      DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("Home Decor (Product3 - P66780)");
      DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("Electronics (Product4 - P66781)");
      node.add(node1);
      node.add(node2);
      node.add(node3);
      node.add(node4);
      DefaultMutableTreeNode one = new DefaultMutableTreeNode("Shirt");
      DefaultMutableTreeNode two = new DefaultMutableTreeNode("T-shirt");
      DefaultMutableTreeNode three = new DefaultMutableTreeNode("Hoodie");
      DefaultMutableTreeNode four = new DefaultMutableTreeNode("Sunglasses");
      DefaultMutableTreeNode five = new DefaultMutableTreeNode("Frames");
      DefaultMutableTreeNode six = new DefaultMutableTreeNode("Belts");
      DefaultMutableTreeNode seven = new DefaultMutableTreeNode("Showpieces & Figurines");
      DefaultMutableTreeNode eight = new DefaultMutableTreeNode("Clocks");
      DefaultMutableTreeNode nine = new DefaultMutableTreeNode("Wall Shelves");
      DefaultMutableTreeNode ten = new DefaultMutableTreeNode("Mobile Accessories");
      DefaultMutableTreeNode eleven = new DefaultMutableTreeNode("Smart Wearable Tech");
      DefaultMutableTreeNode twelve = new DefaultMutableTreeNode("Health Care Applicances");
      DefaultMutableTreeNode thirteen = new DefaultMutableTreeNode("Smart Home Automation");
      node1.add(one);
      node1.add(two);
      node1.add(three);
      node2.add(four);
      node2.add(five);
      node2.add(six);
      node3.add(seven);
      node3.add(eight);
      node3.add(nine);
      node4.add(ten);
      node4.add(eleven);
      node4.add(twelve);
      node4.add(thirteen);
      JTree tree = new JTree(node);
      for (int i = 0; i < tree.getRowCount(); i++) {
         tree.expandRow(i);
      }
      tree.putClientProperty("JTree.lineStyle", "Angled");
      System.out.println("Next leaf after this node = "+three.getNextLeaf());
      tree.setRowHeight(25);
      frame.add(tree);
      frame.setSize(600,450);
      frame.setVisible(true);
   }
}

输出如下,在控制台(Console)上显示此节点之后的叶子 −

以下是我们用于演示的 JTree −

更新时间: 30-Jul-2019

116 次浏览

开启你的 职业生涯

完成课程获得认证

立即开始
广告