Expands a JTree path step by step. - Java Swing

Java examples for Swing:JTree

Description

Expands a JTree path step by step.

Demo Code


//package com.java2s;

import java.util.Stack;

import javax.swing.JTree;

import javax.swing.tree.TreePath;

public class Main {
    /**//from   w  w w . ja va  2  s .c  om
     * Expands a path step by step. First the path with not parents will be
     * expanded, then the child path of this, then the child path of the
     * child path until the last path component is reached.
     *
     * @param tree tree
     * @param path path to expand in <code>tree</code>
     */
    public static void expandPathCascade(JTree tree, TreePath path) {
        if (tree == null) {
            throw new NullPointerException("tree == null");
        }
        if (path == null) {
            throw new NullPointerException("path == null");
        }
        Stack<TreePath> stack = new Stack<>();
        TreePath parent = path;
        while (parent != null) {
            stack.push(parent);
            parent = parent.getParentPath();
        }
        while (!stack.isEmpty()) {
            tree.expandPath(stack.pop());
        }
    }

    /**
     * ?ffnet den Tree auch, wenn das letzte Element eines Pfads ein Blatt ist.
     *
     * @param tree Tree
     * @param path Pfad
     */
    public static void expandPath(JTree tree, TreePath path) {
        if (tree == null) {
            throw new NullPointerException("tree == null");
        }
        if (path == null) {
            throw new NullPointerException("path == null");
        }
        TreePath expandPath = path;
        if (tree.getModel().isLeaf(path.getLastPathComponent())) {
            expandPath = path.getParentPath();
        }
        tree.expandPath(expandPath);
    }
}

Related Tutorials