4

I have a classic JTree populated with some nods. Lets assume tree looks like this:

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

Is there any way in java to check if node exists using assumed path like this:

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

so if node in given location exists it's returned, if not null is returned? Is there any such mechanism in Java?

4

3 回答 3

5

你可能会沿着这些思路尝试一些东西。

树节点位置

示例输出

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

树节点位置.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();
            }
        });
    }
}
于 2012-06-05T04:50:13.847 回答
2

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

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

您可以以此为基础来实现您所追求的。

于 2012-06-04T17:00:05.600 回答
2

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

于 2012-06-04T16:50:18.160 回答