java - 使用路径检查 JTree 节点是否存在

标签 java swing jtree

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

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

Java 中是否有任何方法可以使用这样的假定路径检查节点是否存在:

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

因此,如果给定位置的节点存在,则返回它,如果不存在,则返回 null? Java有没有这样的机制?

最佳答案

您可以按照这些思路尝试一些东西。

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();
            }
        });
    }
}

关于java - 使用路径检查 JTree 节点是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10883293/

相关文章:

java - 可以找到一个字符串数组值是否等于任何随机类型的字符串?

java - 单元 : How to write test case using jUnit and Mockito

java - 加载图形布局时 Eclipse 崩溃

java - 事件处理问题 - Java

java - 无法设置默认按钮 (btn) : no object to call upon

java - 如何从文件中删除绝对路径?

javascript - 在服务器端解压LZString(java)

java - Swing:paintComponent 不会绘制到 JPanel

java - 将 JTree 转换为 XML

java - JTree 首次加载时不显示句柄