使用path检查JTree节点是否存在

时间:2012-06-04 14:47:25

标签: java swing jtree

我有一个经典的JTree填充了一些点头。假设树看起来像这样:

Root
|-Fruit
|--Apple
|--Orange
|-Objects
|--Table
|--Car

java中有没有办法检查节点是否存在使用假定路径,如下所示:

TreeNode found = model.getNodeOrNull("\\Fruit\\Apple")

所以如果给定位置的节点存在则返回,如果不是null则返回? Java中是否有这样的机制?

3 个答案:

答案 0 :(得分:5)

您可以尝试沿着这些方向进行尝试。

Tree Node Location

示例输出

food:pizza found true
od:pizza found false
sports:hockey found true
sports:hockey2 found false

TreeNodeLocation.java

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.Position;
import javax.swing.tree.TreePath;

public class TreeNodeLocation {

    private JTree tree = new JTree();

    TreeNodeLocation() {
        JPanel p = new JPanel(new BorderLayout(2,2));

        final JTextField find = new JTextField("food:pizza");
        find.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                boolean found = findText(find.getText());
                System.out.println(find.getText() + " found " + found);
            }
        });
        p.add(find, BorderLayout.PAGE_START);

        tree.setVisibleRowCount(8);
        for (int row=tree.getRowCount(); row>=0; row--) {
            tree.expandRow(row);
        }

        p.add(new JScrollPane(tree),BorderLayout.CENTER);

        JOptionPane.showMessageDialog(null, p);
    }

    public boolean findText(String nodes) {
        String[] parts = nodes.split(":");
        TreePath path = null;
        for (String part : parts) {
            int row = (path==null ? 0 : tree.getRowForPath(path));
            path = tree.getNextMatch(part, row, Position.Bias.Forward);
            if (path==null) {
                return false;
            }
        }
        tree.scrollPathToVisible(path);
        tree.setSelectionPath(path);

        return path!=null;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TreeNodeLocation();
            }
        });
    }
}

答案 1 :(得分:2)

您可以使用模型的Enumeration个实例之一进行搜索,如here所示。

答案 2 :(得分:2)

不幸的是,没有任何开箱即用的功能。这对Swing不希望强加其设计的节点做出一些假设,因为它会限制它在树中的节点意味着什么(即所有节点都有某种唯一标识它们的字符串)。这并不意味着你自己不能轻易实现它。您可能知道TreePath在JTree中是一个常见的想法,所以这是一个简单的方法,它将TreePath返回给定路径的节点:

http://www.exampledepot.8waytrips.com/egs/javax.swing.tree/FindNode.html

您可以将其作为实现目标的基础。

相关问题