get JTree Path - Java Swing

Java examples for Swing:JTree

Description

get JTree Path

Demo Code


//package com.java2s;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;

import java.util.Enumeration;

import java.util.List;

import java.util.Stack;
import java.util.StringTokenizer;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.TreeModel;

import javax.swing.tree.TreePath;

public class Main {
    /**/*from   ww  w  .  j  av a  2 s .c  o m*/
     * Liefert aus einem Model den Pfad anhand eines Strings, der diesen
     * spezifiziert.
     *
     * @param treeModel     Model
     * @param pathString    String mit Pfad
     * @param pathSeparator Separator zwischen den einzelnen Pfadbestandteilen
     * @return              Pfad oder null, wenn nicht gefunden
     */
    public static TreePath getTreePath(TreeModel treeModel,
            String pathString, String pathSeparator) {
        if (treeModel == null) {
            throw new NullPointerException("treeModel == null");
        }
        if (pathString == null) {
            throw new NullPointerException("pathString == null");
        }
        if (pathSeparator == null) {
            throw new NullPointerException("pathSeparator == null");
        }
        StringTokenizer tokenizer = new StringTokenizer(pathString,
                pathSeparator);
        int tokenCount = tokenizer.countTokens();
        int tokenNumber = 1;
        int tokenFoundCount = 0;
        Object[] path = new Object[(tokenCount > 0) ? tokenCount : 1];
        if (tokenCount > 0) {
            path[0] = treeModel.getRoot();
            tokenizer.nextToken();
            Object currentElement = treeModel.getRoot();
            boolean appended = true;
            while (appended && (tokenNumber < tokenCount)) {
                int childCount = treeModel.getChildCount(currentElement);
                String pathToken = tokenizer.nextToken();
                boolean found = false;
                appended = false;
                for (int index = 0; (index < childCount) && !found; index++) {
                    Object childElement = treeModel.getChild(
                            currentElement, index);
                    found = childElement.toString().equals(pathToken);
                    if (found) {
                        path[tokenNumber] = childElement;
                        currentElement = childElement;
                        appended = true;
                        tokenFoundCount++;
                    }
                }
                tokenNumber++;
            }
        }
        return ((tokenCount > 0) && (tokenCount - 1 == tokenFoundCount)) ? new TreePath(
                path) : null;
    }

    /**
     * Returns the tree path below a mouse position got by a mouse event.
     *
     * @param  evt mouse event within a {@code JTree}
     * @return   tree path below the mouse position or null if below the mouse
     *           position isn't a tree path
     */
    public static TreePath getTreePath(MouseEvent evt) {
        if (evt == null) {
            throw new NullPointerException("evt == null");
        }
        Object source = evt.getSource();
        if (source instanceof JTree) {
            int mousePosX = evt.getX();
            int mousePosY = evt.getY();
            return ((JTree) source)
                    .getPathForLocation(mousePosX, mousePosY);
        }
        return null;
    }

    /**
     * Returns the tree path of a file, each path component is a parent
     * (child) file of a file.
     *
     * <em>Expects that the nodes of the tree having the type
     * {@code DefaultMutableTreeNode}!</em>
     *
     * @param  file   file
     * @param  model  model when the root is not a file, else null
     * @return path
     */
    public static TreePath getTreePath(File file, TreeModel model) {
        if (file == null) {
            throw new NullPointerException("file == null");
        }
        if (model == null) {
            throw new NullPointerException("model == null");
        }
        Stack<DefaultMutableTreeNode> stack = new Stack<>();
        File parentFile = file;
        while (parentFile != null) {
            stack.push(new DefaultMutableTreeNode(parentFile));
            parentFile = parentFile.getParentFile();
        }
        List<DefaultMutableTreeNode> nodes = new ArrayList<>(
                stack.size() + 1);
        nodes.add((DefaultMutableTreeNode) model.getRoot());
        while (!stack.isEmpty()) {
            nodes.add(stack.pop());
        }
        return new TreePath(nodes.toArray());
    }

    private static DefaultMutableTreeNode getChild(
            DefaultMutableTreeNode parentNode, String toString,
            boolean ignoreCase) {
        assert toString != null;
        for (Enumeration<?> e = parentNode.children(); e.hasMoreElements();) {
            Object child = e.nextElement();
            if (child instanceof DefaultMutableTreeNode) {
                if (child.toString() == null) {
                    return null;
                }
                boolean exists = ignoreCase ? child.toString()
                        .equalsIgnoreCase(toString) : child.toString()
                        .equals(toString);
                if (exists) {
                    return (DefaultMutableTreeNode) child;
                }
            }
        }
        return null;
    }
}

Related Tutorials