Example usage for javax.swing JTree scrollPathToVisible

List of usage examples for javax.swing JTree scrollPathToVisible

Introduction

In this page you can find the example usage for javax.swing JTree scrollPathToVisible.

Prototype

public void scrollPathToVisible(TreePath path) 

Source Link

Document

Makes sure all the path components in path are expanded (except for the last path component) and scrolls so that the node identified by the path is displayed.

Usage

From source file:Main.java

public static void goToNode(JTree t, TreePath path) {
    t.setSelectionPath(path);
    t.scrollPathToVisible(path);
}

From source file:Main.java

public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TreeNode root = getNodes();//from  w w w  .j  av  a 2  s . c  o m
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree tree = new JTree(model);
    tree.setRootVisible(false);

    JButton add = new JButton("add new");
    add.addActionListener(e -> {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) {
            return;
        }
        MyObject obj = (MyObject) selectedNode.getUserObject();
        MyObject newChild = new MyObject(obj.name + "-" + (obj.childs.size() + 1));
        obj.childs.add(newChild);
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newChild);
        model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
        TreeNode[] nodes = model.getPathToRoot(newNode);
        TreePath path = new TreePath(nodes);
        tree.scrollPathToVisible(path);
    });

    JButton print = new JButton("print childs");
    print.addActionListener(e -> {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) {
            return;
        }
        MyObject obj = (MyObject) selectedNode.getUserObject();
        System.out.println(obj.childs);
    });
    JPanel btns = new JPanel();
    btns.add(add);
    btns.add(print);

    add(new JScrollPane(tree));
    add(btns, BorderLayout.SOUTH);
    pack();
    setVisible(true);
}

From source file:fxts.stations.ui.help.HelpPane.java

/**
 * This method is called when new item selected at content tree
 *
 * @param aId identifer of the page./*from w ww .j  a va2s.  c  om*/
 */
public void onSelectContent(String aId) {
    //if synchronizing of contents mode
    if (mContentSinchronize) {
        mContentSinchronize = false;
        return;
    }

    //check id
    if (aId == null) {
        mLogger.debug("Zero id of page.");
        return;
    }
    if (!mRepaintMode) {
        if (aId.equals(mCurrentPageId)) {
            return;
        }
    }

    //gets url of page by id
    String sUrl = mContentTree.getPageUrl(aId);
    if (sUrl == null) {
        //System.out.println("URL for page with id = " + asId + " not fond");
        return;
    }

    //creates full url
    String sFullUrl = mContentTree.getHelpPrefix();
    if (sFullUrl == null) {
        sFullUrl = "";
    }
    sFullUrl += "/";
    sFullUrl += mResMan.getLocale().toString();
    sFullUrl += "/";
    sFullUrl += sUrl;

    //loads url
    URL url;
    try {
        url = getClass().getClassLoader().getResource(sFullUrl);
    } catch (Exception e) {
        url = null;
    }

    //if localized help not presence
    if (url == null) {
        //creates full url to help on default language
        sFullUrl = mContentTree.getHelpPrefix();
        if (sFullUrl == null) {
            sFullUrl = "";
        }
        sFullUrl += "/";
        sFullUrl += mResMan.getDefaultLocale().toString();
        sFullUrl += "/";
        sFullUrl += sUrl;

        //loads url to help on default language
        try {
            url = getClass().getClassLoader().getResource(sFullUrl);
        } catch (Exception e) {
            url = null;
        }

        //if help this page not presence even at default language
        if (url == null) {
            mLogger.debug("Page by url \"" + sFullUrl + "\" not found!");
            mHtmlPage.setText(mResMan.getString("IDS_HELP_WINDOW_NO_PAGE", "No page with url = ") + sFullUrl);
            return;
        }
    }
    try {
        mHtmlPage.setPage(url);
        //sets last opened page
        mCurrentPageId = aId;

        //if browsing by contents
        if (mContentsBrowsing) {
            //sinchronize contenst
            JTree tree = mContentTree.getTree();
            TreePath rootPath = new TreePath(mContentTree.getTree().getModel().getRoot());
            TreePath path = mContentTree.findPathByUrl(rootPath, sUrl);
            if (path != null) {
                mContentSinchronize = true;
                tree.setSelectionPath(path);
                tree.scrollPathToVisible(path);
            } else {
                mLogger.debug("Contents not synchronized!");
            }
            mContentsBrowsing = false;
        } else {
            //setting browising by contents
            mContentTree.getIterator().setCurrentByUrl(sUrl);
            mUpButton.setEnabled(mContentTree.getIterator().hasPrevious());
            mDownButton.setEnabled(mContentTree.getIterator().hasNext());
        }

        //saving at history
        if (mIsHistorycalStep) {
            mIsHistorycalStep = false;

            //sinchronize contenst
            JTree tree = mContentTree.getTree();
            TreePath rootPath = new TreePath(mContentTree.getTree().getModel().getRoot());
            TreePath path = mContentTree.findPathByUrl(rootPath, sUrl);
            if (path != null) {
                mContentSinchronize = true;
                tree.setSelectionPath(path);
                tree.scrollPathToVisible(path);
            } else {
                mLogger.debug("Contents not synchronized!");
            }
        } else {
            if (!mRepaintMode) {
                mHistory.put(aId);
                mBackButton.setEnabled(mHistory.hasBackStep());
                mForwardButton.setEnabled(mHistory.hasForwardStep());
            } else {
                mRepaintMode = false;
            }
        }
    } catch (Exception e) {
        mLogger.debug("Attempted to read a bad URL: " + url);
        mHtmlPage.setText(mResMan.getString("IDS_HELP_WINDOW_NO_PAGE", "No page with url:") + url.toString());
    }
}

From source file:com.pironet.tda.TDA.java

/**
 * navigate to monitor/*from w  ww .  jav a  2  s .c  o m*/
 *
 * @param monitorLink the monitor link to navigate to
 */
private void navigateToMonitor(String monitorLink) {
    String monitor = monitorLink.substring(monitorLink.lastIndexOf('/') + 1);

    // find monitor node for this thread info
    DefaultMutableTreeNode dumpNode;
    if (monitorLink.indexOf("Dump No.") > 0) {
        dumpNode = getDumpRootNode(
                monitorLink.substring(monitorLink.indexOf('/') + 1, monitorLink.lastIndexOf('/')),
                (DefaultMutableTreeNode) tree.getLastSelectedPathComponent());
    } else {
        dumpNode = getDumpRootNode((DefaultMutableTreeNode) tree.getLastSelectedPathComponent());
    }
    final Enumeration children = dumpNode.children();
    DefaultMutableTreeNode monitorNode = null;
    DefaultMutableTreeNode monitorWithoutLocksNode = null;
    while (children.hasMoreElements()) {
        DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
        if (child.getUserObject() instanceof TreeCategory) {
            if (((TreeCategory) child.getUserObject()).getName().startsWith("Monitors (")) {
                monitorNode = child;
            } else if (((TreeCategory) child.getUserObject()).getName().startsWith("Monitors without")) {
                monitorWithoutLocksNode = child;
            }
        }
    }

    // highlight chosen monitor
    JTree searchTree = (JTree) ((TreeCategory) monitorNode.getUserObject()).getCatComponent(this);
    TreePath searchPath = searchTree.getNextMatch(monitor, 0, Position.Bias.Forward);
    if ((searchPath == null) && (monitorWithoutLocksNode != null)) {
        searchTree = (JTree) ((TreeCategory) monitorWithoutLocksNode.getUserObject()).getCatComponent(this);
        searchPath = searchTree.getNextMatch(monitor, 0, Position.Bias.Forward);
        monitorNode = monitorWithoutLocksNode;
    }

    if (searchPath != null) {
        TreePath monitorPath = new TreePath(monitorNode.getPath());
        tree.setSelectionPath(monitorPath);
        tree.scrollPathToVisible(monitorPath);

        displayCategory(monitorNode.getUserObject());

        TreePath threadInMonitor = searchPath
                .pathByAddingChild(((DefaultMutableTreeNode) searchPath.getLastPathComponent()).getLastChild());
        searchTree.setSelectionPath(threadInMonitor);
        searchTree.scrollPathToVisible(searchPath);
        searchTree.setSelectionPath(searchPath);
    }
}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenter.java

public void selectNode(Object nodeObject, ETreeType treeType) {
    JTree tree = getTree(treeType);
    DepositTreeModel model = (DepositTreeModel) tree.getModel();
    DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) model.getRoot();
    DefaultMutableTreeNode node = findNode(rootNode, nodeObject);
    if (node != null) {
        LOG.debug("selectNode Node object found");
        TreePath path = new TreePath(node.getPath());
        tree.scrollPathToVisible(path);
        tree.setSelectionPath(path);/*  w w w  .  ja  v  a  2  s  . com*/
    } else {
        LOG.debug("selectNode Node object not found");
    }
}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenter.java

public void addChildFiles(DefaultMutableTreeNode rootNode, FSOCollection children, DepositTreeModel model,
        String pathToDisplay, JTree whichTree) {
    LOG.debug("addChildFiles, root: " + rootNode.getUserObject());
    model.reload(rootNode);//from   w  w w  .  j  a v a 2 s  .  co  m
    /*      for (FileSystemObject fso : children) {
             if (fso.getFile() == null) {
    LOG.debug("add child (file is null): " + fso.getDescription());
             } else {
    LOG.debug("add child (file is not null): "
          + fso.getDescription());
             }
             if ((!model.getTreeType().equals(ETreeType.FileSystemTree))
       || (!fso.getIsFile()) || (!fileIsInEntity(fso))) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode();
    node.setUserObject(fso);
    model.insertNodeInto(node, rootNode, rootNode.getChildCount());
    addChildFiles(node, fso.getChildren(), model, pathToDisplay,
          whichTree);
    if ((pathToDisplay != null)
          && (pathToDisplay.equals(fso.getFullPath()))) {
       expandNode(whichTree, node, false);
       whichTree.scrollPathToVisible(new TreePath(node.getPath()));
    }
             }
          }*/
    for (int i = 0; i < children.size(); i++) {
        FileSystemObject fso = children.get(i);
        if (fso.getFile() == null) {
            LOG.debug("add child (file is null): " + fso.getDescription());
        } else {
            LOG.debug("add child (file is not null): " + fso.getDescription());
        }
        if ((!model.getTreeType().equals(ETreeType.FileSystemTree)) || (!fso.getIsFile())
                || (!fileIsInEntity(fso))) {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode();
            node.setUserObject(fso);
            model.insertNodeInto(node, rootNode, rootNode.getChildCount());
            addChildFiles(node, fso.getChildren(), model, pathToDisplay, whichTree);
            if ((pathToDisplay != null) && (pathToDisplay.equals(fso.getFullPath()))) {
                expandNode(whichTree, node, false);
                whichTree.scrollPathToVisible(new TreePath(node.getPath()));
            }
        }
    }
}

From source file:org.executequery.gui.browser.TreeFindAction.java

private void changeSelection(JTree tree, TreePath path) {
    tree.setSelectionPath(path);
    tree.scrollPathToVisible(path);
}

From source file:org.mbari.aved.ui.classifier.knowledgebase.SearchableConceptTreePanel.java

/**
 * Loads the branch of a particular concept. This method does the following
 * <ol>//from  w  w w.java 2  s . c o m
 *      <li>Walks from the concept up the tree to the root concept, storing
 *      the concepts in a list. (This is very fast)</li>
 *  <li>Starts walking from the root down (using lazyExpand), searching each
 *      childnode for a matching primary name (which was stored in the first
 *      step</li>
 *  <li>If a matching primary name is found this stops otherwise
 *              it opens the next level and searches for the next mathc in the list.</li>
 *  <li></li>
 * </ol>
 * @param concept
 */
private void openNode(final Concept concept) {
    if (log.isDebugEnabled()) {
        log.debug("Opening node containing " + concept);
    }

    if (concept == null) {
        return;
    }

    // Get the list of concepts up to root
    final LinkedList conceptList = new LinkedList();
    Concept c = concept;

    while (c != null) {
        conceptList.add(c);
        c = (Concept) c.getParentConcept();
    }

    // Walk the tree from root on down opening nodes as we go
    final ListIterator i = conceptList.listIterator(conceptList.size());

    // Skip the root
    i.previous();

    final JTree tree = getJTree();
    final DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
    final DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) treeModel.getRoot();
    TreePath path = new TreePath(rootNode.getPath());

    tree.setSelectionPath(path);

    DefaultMutableTreeNode parentNode = rootNode;

    while (i.hasPrevious()) {
        c = (Concept) i.previous();

        final TreeConcept parentTreeConcept = (TreeConcept) parentNode.getUserObject();

        parentTreeConcept.lazyExpand(parentNode);

        // treeModel.reload(parentNode);
        final Enumeration enm = parentNode.children();

        while (enm.hasMoreElements()) {
            final DefaultMutableTreeNode node = (DefaultMutableTreeNode) enm.nextElement();
            final TreeConcept tc = (TreeConcept) node.getUserObject();

            if (tc.getName().equals(c.getPrimaryConceptNameAsString())) {
                parentNode = node;

                break;
            }
        }
    }

    final TreeNode _parentNode = parentNode;

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            treeModel.reload(_parentNode);
            tree.scrollPathToVisible(new TreePath(_parentNode));
        }
    });
}