Example usage for javax.swing JTree setSelectionPath

List of usage examples for javax.swing JTree setSelectionPath

Introduction

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

Prototype

public void setSelectionPath(TreePath path) 

Source Link

Document

Selects the node identified by the specified path.

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

private void myPopupEvent(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    JTree tree = (JTree) e.getSource();
    TreePath path = tree.getPathForLocation(x, y);
    if (path == null)
        return;//  w  w  w. j  a v a 2 s.co m

    DefaultMutableTreeNode rightClickedNode = (DefaultMutableTreeNode) path.getLastPathComponent();

    TreePath[] selectionPaths = tree.getSelectionPaths();

    boolean isSelected = false;
    if (selectionPaths != null) {
        for (TreePath selectionPath : selectionPaths) {
            if (selectionPath.equals(path)) {
                isSelected = true;
            }
        }
    }
    if (!isSelected) {
        tree.setSelectionPath(path);
    }
    if (rightClickedNode.isLeaf()) {
        JPopupMenu popup = new JPopupMenu();
        final JMenuItem refreshMenuItem = new JMenuItem("refresh");
        refreshMenuItem.addActionListener(ev -> System.out.println("refresh!"));
        popup.add(refreshMenuItem);
        popup.show(tree, x, y);
    }
}

From source file:TreeIt.java

public TreeIt() {
    JFrame f = new JFrame();
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Calendar");
    DefaultMutableTreeNode months = new DefaultMutableTreeNode("Months");
    root.add(months);//from w  ww.j  av a 2 s . c o m
    String monthLabels[] = { "January", "February", "March", "April", "May", "June", "July", "August",
            "September", "October", "November", "December" };
    for (int i = 0, n = monthLabels.length; i < n; i++)
        months.add(new DefaultMutableTreeNode(monthLabels[i]));
    DefaultMutableTreeNode weeks = new DefaultMutableTreeNode("Weeks");
    root.add(weeks);
    String weekLabels[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
    for (int i = 0, n = weekLabels.length; i < n; i++)
        weeks.add(new DefaultMutableTreeNode(weekLabels[i]));
    JTree jt = new JTree(root);
    jt.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            TreePath path = e.getPath();
            System.out.println("Picked: " + path.getLastPathComponent());
            Object elements[] = path.getPath();
            for (int i = 0, n = elements.length; i < n; i++) {
                System.out.print("->" + elements[i]);
            }
            System.out.println();
        }
    });

    DefaultMutableTreeNode lastLeaf = root.getLastLeaf();
    TreePath path = new TreePath(lastLeaf.getPath());
    jt.setSelectionPath(path);

    jt.setCellRenderer(new MyCellRenderer());

    JScrollPane jsp = new JScrollPane(jt);
    Container c = f.getContentPane();
    c.add(jsp, BorderLayout.CENTER);
    f.setSize(250, 250);
    f.show();
}

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

/**
 * This method is called when hyperlink activated.
 *
 * @param aUrl url to page.//from  www . j  a v  a 2 s.  c o m
 */
public void onSelectContentByHyperlink(URL aUrl) {
    if (aUrl == null) {
        mLogger.debug("Hyperlink is null!");
        return;
    }
    try {
        mHtmlPage.setPage(aUrl);
        String sUrl = getShortUrl(aUrl);
        if (sUrl != null) {
            //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);
            } else {
                //System.out.println("Contents not synchronized!");
            }

            //setting browising by contents
            mContentTree.getIterator().setCurrentByUrl(sUrl);
            mUpButton.setEnabled(mContentTree.getIterator().hasPrevious());
            mDownButton.setEnabled(mContentTree.getIterator().hasNext());

            //saving at history
            String sId = mContentTree.getPageId(sUrl);
            mHistory.put(sId);
            mBackButton.setEnabled(mHistory.hasBackStep());
            mForwardButton.setEnabled(mHistory.hasForwardStep());

            //sets last opened page
            mCurrentPageId = sId;
        } else {
            mLogger.debug("Short url not found for full url = " + aUrl.toString());
        }
    } catch (Exception e) {
        mLogger.error("Attempted to read a bad URL from hyperlink: " + aUrl);
        mHtmlPage.setText(mResMan.getString("IDS_HELP_WINDOW_NO_PAGE", "No page with url:") + aUrl.toString());
    }
}

From source file:Main.java

public Main() {
    super(BoxLayout.Y_AXIS);
    glassPane.setOpaque(false);/*from  w  w w  . ja  va2  s . c o  m*/
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    for (int i = 0; i < 14000; i++) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode("Root" + i);
        node.add(new DefaultMutableTreeNode("Child" + i));
        root.add(node);
    }

    final JTree tree = new JTree(root);
    tree.setRootVisible(false);
    final JScrollPane pane = new JScrollPane(tree);
    add(pane);

    JButton button = new JButton("Expand");
    button.addActionListener(e -> {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                TreePath[] paths = tree.getSelectionPaths();
                if (paths == null || paths.length == 0) {
                    glassPane.setVisible(false);
                    return;
                }
                tree.setSelectionPath(paths[0]);

                for (int i = 0; i < paths.length; i++) {
                    tree.expandPath(paths[i]);
                }
                glassPane.setVisible(false);
            }
        });
        getRootPane().setGlassPane(glassPane);
        glassPane.setVisible(true);
        t.start();
    });
    add(button);
    glassPane.addMouseWheelListener(e -> {
        for (MouseWheelListener mwl : pane.getMouseWheelListeners()) {
            mwl.mouseWheelMoved(e);
        }
    });
}

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 w w.  j ava 2 s. c  o  m*/
 */
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:ca.sqlpower.architect.swingui.enterprise.SecurityPanel.java

public SecurityPanel(SPServerInfo serverInfo, Action closeAction, Dialog d, ArchitectSession session) {
    this.closeAction = closeAction;

    splitpane = new JSplitPane();
    panel = new JPanel();

    ArchitectClientSideSession clientSideSession = ArchitectClientSideSession.getSecuritySessions()
            .get(serverInfo.getServerAddress());

    //Displaying an indeterminate progress bar in place of the split pane
    //until the security session has loaded fully.
    if (clientSideSession.getUpdater().getRevision() <= 0) {
        JLabel messageLabel = new JLabel("Opening");
        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);

        DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("pref:grow, 5dlu, pref"));
        builder.setDefaultDialogBorder();
        builder.append(messageLabel, 3);
        builder.nextLine();/*w  w  w  .  j a va  2 s.  c  o  m*/
        builder.append(progressBar, 3);

        UpdateListener l = new UpdateListener() {

            @Override
            public void workspaceDeleted() {
                //do nothing
            }

            @Override
            public boolean updatePerformed(AbstractNetworkConflictResolver resolver) {
                panel.removeAll();
                panel.add(splitpane);
                dialog.pack();
                refreshTree();
                return true;
            }

            @Override
            public boolean updateException(AbstractNetworkConflictResolver resolver, Throwable t) {
                //do nothing, the error will be handled elsewhere
                return true;
            }

            @Override
            public void preUpdatePerformed(AbstractNetworkConflictResolver resolver) {
                //do nothing
            }
        };

        clientSideSession.getUpdater().addListener(l);
        panel.add(builder.getPanel());
    }
    this.securityWorkspace = clientSideSession.getWorkspace();
    this.username = serverInfo.getUsername();
    this.dialog = d;
    this.session = session;

    try {
        digester = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    rootNode.add(usersNode);
    rootNode.add(groupsNode);

    rightSidePanel = new JPanel();

    tree = new JTree(rootNode);
    tree.addTreeSelectionListener(treeListener);
    tree.setRootVisible(false);
    tree.setShowsRootHandles(true);
    tree.setCellRenderer(new DefaultTreeCellRenderer() {
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
            if (userObject instanceof User) {
                setIcon(USER_ICON);
            } else if (userObject instanceof Group) {
                setIcon(GROUP_ICON);
            }
            return this;
        }
    });

    treePane = new JScrollPane(tree);
    treePane.setPreferredSize(new Dimension(200, treePane.getPreferredSize().height));

    tree.addMouseListener(popupListener);

    splitpane.setRightComponent(rightSidePanel);
    splitpane.setLeftComponent(treePane);

    if (clientSideSession.getUpdater().getRevision() > 0) {
        panel.removeAll();
        panel.add(splitpane);
    }

    refreshTree();

    try {
        tree.setSelectionPath(new TreePath(usersNode.getFirstChild()));
    } catch (NoSuchElementException e) {
    } // This just means that the node has no children, so we cannot expand the path.
}

From source file:it.imtech.metadata.MetaUtility.java

/**
 * Aggiunge il pannello delle classificazioni all'interfaccia dei metadati
 *
 * @param innerPanel Pannello sul quale aggiungere i metadati
 * @param kv Valori dei metadati/*from w  ww .j  a v a  2s. c o m*/
 */
private void addClassification(JPanel innerPanel, Integer kv, final String sequence, final String panelname)
        throws Exception {
    try {
        ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE,
                Globals.loader);

        DefaultMutableTreeNode hierarchy = new DefaultMutableTreeNode("root");
        selected = null;
        String selectedPath = "";

        String link = selectedClassificationList.get(panelname + "---" + sequence);

        recursiveOefosTreeviewBuild(hierarchy, oefos.get(link), sequence, panelname);
        DefaultTreeModel model = new DefaultTreeModel(hierarchy);

        final JTree tree = new JTree(model);
        tree.setRootVisible(false);

        if (selected != null) {
            TreePath selpath = new TreePath(selected.getPath());
            tree.setSelectionPath(selpath);

            Object[] nodes = selpath.getPath();

            for (int i = 1; i < nodes.length; i++) {
                selectedPath += nodes[i].toString();
                selectedPath += (i != nodes.length - 1) ? "/" : "";
            }
        }

        tree.setName("MID_" + Integer.toString(kv) + "---" + sequence);
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

        tree.addTreeSelectionListener(new TreeSelectionListener() {

            public void valueChanged(TreeSelectionEvent e) {
                try {
                    setOEFOS(tree, sequence, panelname);
                } catch (Exception ex) {
                    logger.error(ex.getMessage());
                }
            }
        });

        javax.swing.JScrollPane tree_scroller = new javax.swing.JScrollPane();
        tree_scroller
                .setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        tree_scroller.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        tree_scroller.setViewportView(tree);
        tree_scroller.setBorder(null);

        innerPanel.add(tree_scroller, "wrap, width 100:800:800");

        JPanel iPanel = new JPanel(new MigLayout());
        iPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
                Utility.getBundleString("choose2", bundle), TitledBorder.LEFT, TitledBorder.TOP));
        JLabel label = new JLabel();
        label.setName("classification_path" + "---" + sequence);
        label.setText(selectedPath);
        iPanel.add(label, "wrap, growx, height 30:30:30");

        innerPanel.add(iPanel, "wrap, width 100:800:800");

        findLastClassification(panelname);

    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw new Exception("Exception in addClassification: " + ex.getStackTrace() + "\n");
    }
}

From source file:it.imtech.metadata.MetaUtility.java

/**
 * Metodo che setta il TreeMap oefos_path con i valori del nodo selezionato
 * e aggiorna il label che descrive il path dei nodi selezionati
 *
 * @param e L'albero sul quale ricercare il path selezionato
 *///from   ww  w .ja va2 s . c o  m
private void setOEFOS(JTree e, String sequence, String panelname) throws Exception {
    try {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getLastSelectedPathComponent();
        String completePath = "";
        //OefosPaths path = new OefosPaths(panelname, sequence);

        BookImporter.getInstance()
                .createComponentMap(BookImporter.getInstance().metadatapanels.get(panelname).getPanel());
        Component controls = BookImporter.getInstance().getComponentByName("classification_path---" + sequence);

        //Se e' una foglia aggiorna il path nell'interfaccia e oefos_path
        if (node != null) {
            TreePath selpath = new TreePath(node.getPath());
            e.setSelectionPath(selpath);

            Object[] nodes = selpath.getPath();

            TreeMap<Integer, Integer> single_path = new TreeMap<Integer, Integer>();

            for (int i = 1; i < nodes.length; i++) {
                Object nodeInfo = nodes[i];
                DefaultMutableTreeNode nodeC = (DefaultMutableTreeNode) nodeInfo;
                ClassNode c = (ClassNode) nodeC.getUserObject();
                single_path.put(i, Integer.parseInt(c.getKey().toString()));

                completePath += nodes[i].toString();
                completePath += (i != nodes.length - 1) ? "/" : "";
            }

            this.oefos_path.put(panelname + "----" + sequence, single_path);
        } else {
            this.oefos_path.put(panelname + "----" + sequence, null);
        }

        JLabel label = (JLabel) controls;
        if (completePath.length() > 120) {
            label.setText(completePath.substring(0, 120));
        } else {
            label.setText(completePath);
        }

        label.revalidate();
    } catch (Exception ex) {
        throw new Exception("Exception in setOEFOS: " + ex.getStackTrace() + "\n");
    }
}

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

/**
 * navigate to monitor/*w  w  w . ja va2s  . com*/
 *
 * @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);
    }
}