如何使用 Java 在 JTree 组件中找到节点?


要查找 JTree 组件中的节点,请使用 getNextMatch() 方法。此处,我们尝试查找以 “A” 字符开头的节点。从使用 begnRow 变量设置的以下节点开始搜索 −

int begnRow = 0;
String prefix = "A"; TreePath treePath = tree.getNextMatch(prefix, begnRow, Position.Bias.Forward);

我们已在控制台中显示结果节点 −

System.out.println("Node = "+treePath);

以下是如何使用 Java 查找 JTree 组件中的节点的示例 −

package my;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
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);
      int begnRow = 0;
      String prefix = "A"; TreePath treePath = tree.getNextMatch(prefix, begnRow, Position.Bias.Forward); System.out.println("Node = "+treePath);
      tree.setRowHeight(25);
      frame.add(tree);
      frame.setSize(550,400);
      frame.setVisible(true);
   }
}

输出

输出如下。运行时,可以看到要查找的节点 −

更新于: 30-Jul-2019

686 次浏览

启动你的事业

完成课程后获得认证

开始
广告