Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if JTree node exist using path

Tags:

java

swing

jtree

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?

like image 234
guest86 Avatar asked Jan 17 '23 12:01

guest86


2 Answers

You might experiment with something along these lines.

Tree Node Location

Example Output

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();
            }
        });
    }
}
like image 59
Andrew Thompson Avatar answered Jan 19 '23 02:01

Andrew Thompson


You can search using one of model's Enumeration instances, as shown here.

like image 26
trashgod Avatar answered Jan 19 '23 02:01

trashgod