Example usage for javax.swing.tree DefaultMutableTreeNode getPath

List of usage examples for javax.swing.tree DefaultMutableTreeNode getPath

Introduction

In this page you can find the example usage for javax.swing.tree DefaultMutableTreeNode getPath.

Prototype

public TreeNode[] getPath() 

Source Link

Document

Returns the path from the root, to get to this node.

Usage

From source file:DynamicTreeDemo.java

public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible) {
    DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);

    if (parent == null) {
        parent = rootNode;//w w w.j  a  v a 2 s  . c om
    }

    // It is key to invoke this on the TreeModel, and NOT DefaultMutableTreeNode
    treeModel.insertNodeInto(childNode, parent, parent.getChildCount());

    // Make sure the user can see the lovely new node.
    if (shouldBeVisible) {
        tree.scrollPathToVisible(new TreePath(childNode.getPath()));
    }
    return childNode;
}

From source file:edu.mbl.jif.datasetconvert.CheckboxTreeDimensions.java

/**
 * Initialize the tree.//  w  w w. j  a v  a 2  s  . c  o m
 *
 */
private JScrollPane getCheckboxTree() {
    if (this.checkboxTree == null) {
        this.checkboxTree = new CheckboxTree(getDimensionsTreeModel(sumMD));
        //this.checkboxTree.addKeyListener(new RefreshListener());

        System.out.println(this.checkboxTree.toString());

        this.checkboxTree.getCheckingModel().setCheckingMode(TreeCheckingModel.CheckingMode.PROPAGATE);
        this.checkboxTree.setRootVisible(true);
        this.checkboxTree.setEnabled(true);
        this.checkboxTree.expandAll();

        DefaultMutableTreeNode mn = (DefaultMutableTreeNode) this.checkboxTree.getModel().getRoot();
        //         mn = (DefaultMutableTreeNode) mn.getChildAt(2);
        //         mn = (DefaultMutableTreeNode) mn.getChildAt(2);

        //         System.out.println("row number: " + this.checkboxTree.getRowForPath(new TreePath(mn.getPath())));

        this.checkboxTree.addCheckingPath(new TreePath(mn.getPath()));

        this.checkboxTree.addTreeCheckingListener(new TreeCheckingListener() {
            public void valueChanged(TreeCheckingEvent e) {
                System.out.println("checking set changed, leading path: "
                        + ((TreeNode) e.getPath().getLastPathComponent()).toString());
                System.out.println("checking roots: ");
                TreePath[] cr = CheckboxTreeDimensions.this.checkboxTree.getCheckingRoots();
                for (TreePath path : cr) {
                    System.out.println(path.getLastPathComponent());
                }
                System.out.println("\nPaths: ");
                TreePath[] cp = CheckboxTreeDimensions.this.checkboxTree.getCheckingPaths();
                for (TreePath path : cp) {
                    System.out.println(path.toString());
                }
            }
        });
    }
    return new JScrollPane(this.checkboxTree);
}

From source file:hr.fer.zemris.vhdllab.view.explorer.ProjectExplorerView.java

private Project getProjectForSelectedFile() {
    DefaultMutableTreeNode node = getLastSelectedNode();
    TreeNode[] path = node.getPath();
    DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) path[1];
    return (Project) projectNode.getUserObject();
}

From source file:uk.co.markfrimston.tasktree.Main.java

public Main(TaskTree taskTree) {
    super();/* w w  w .  j a  va  2 s . com*/

    this.taskTree = taskTree;

    this.setTitle("Task Tree");
    this.setSize(new Dimension(300, 500));
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel quickInPanel = new JPanel(new BorderLayout());
    this.quickIn = new JTextArea();
    this.quickIn.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent arg0) {
            if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
                String newText = quickIn.getText().trim();
                if (newText != null && newText.length() > 0) {
                    addTask(Main.this.taskTree.getRoot(), 0, newText, true);
                    try {
                        Main.this.taskTree.changesMade();
                    } catch (Exception e) {
                        error(e.getMessage());
                    }
                }
                quickIn.setText("");
            }
        }
    });
    this.quickIn.setPreferredSize(new Dimension(300, 75));
    this.quickIn.setBorder(BorderFactory.createTitledBorder("Quick Input"));
    quickInPanel.add(this.quickIn, BorderLayout.CENTER);
    this.syncButton = new JButton("Sync");
    this.syncButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new SyncThread(Main.this).start();
        }
    });
    quickInPanel.add(this.syncButton, BorderLayout.EAST);
    this.getContentPane().add(quickInPanel, BorderLayout.NORTH);

    this.tree = new JTree(taskTree.getTreeModel());
    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer() {
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
            Object newVal = htmlFilter(String.valueOf(node.getUserObject()));
            if (node.getChildCount() > 0 && !tree.isExpanded(new TreePath(node.getPath()))) {
                DefaultMutableTreeNode firstLeaf = (DefaultMutableTreeNode) node.getFirstLeaf();
                newVal = htmlFilter(String.valueOf(node.getUserObject()))
                        + " <span style='color:silver;font-style:italic'>" + "("
                        + String.valueOf(firstLeaf.getUserObject()) + ")</span>";
            }
            newVal = "<html>" + newVal + "</html>";

            return super.getTreeCellRendererComponent(tree, newVal, selected, expanded, leaf, row, hasFocus);
        }
    };
    ImageIcon bulletIcon = new ImageIcon(Main.class.getResource("bullet.gif"));
    renderer.setLeafIcon(bulletIcon);
    renderer.setOpenIcon(bulletIcon);
    renderer.setClosedIcon(bulletIcon);
    renderer.setBorder(BorderFactory.createEmptyBorder(4, 0, 4, 0));
    this.tree.setCellRenderer(renderer);
    this.tree.setRootVisible(false);
    this.tree.setShowsRootHandles(true);
    this.tree.addMouseListener(new MouseAdapter() {
        protected void doSelectRow(MouseEvent arg0) {
            int row = tree.getRowForLocation(arg0.getX(), arg0.getY());
            if (row != -1) {
                tree.setSelectionRow(row);
                if (arg0.isPopupTrigger()) {
                    popup.show(tree, arg0.getX(), arg0.getY());
                }
            }
        }

        public void mousePressed(MouseEvent arg0) {
            doSelectRow(arg0);
        }

        public void mouseReleased(MouseEvent arg0) {
            doSelectRow(arg0);
        }
    });
    JScrollPane treeScroll = new JScrollPane(tree);
    treeScroll.setBorder(BorderFactory.createTitledBorder("Task List"));
    this.getContentPane().add(treeScroll, BorderLayout.CENTER);

    this.popup = new JPopupMenu();
    JMenuItem addBefore = new JMenuItem("Add Before");
    addBefore.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            int pos = parent.getIndex(selected);
            promptAndInsert(parent, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(addBefore);
    JMenuItem addAfter = new JMenuItem("Add After");
    addAfter.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            int pos = parent.getIndex(selected) + 1;
            promptAndInsert(parent, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(addAfter);
    JMenuItem addNested = new JMenuItem("Add Nested");
    addNested.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            int pos = selected.getChildCount();
            promptAndInsert(selected, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                ex.getMessage();
            }
        }
    });
    this.popup.add(addNested);
    this.popup.add(new JSeparator());
    JMenuItem moveTop = new JMenuItem("Move to Top");
    moveTop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            moveTask(selected, parent, 0);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(moveTop);
    JMenuItem moveUp = new JMenuItem("Move Up");
    moveUp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            int pos = Math.max(parent.getIndex(selected) - 1, 0);
            moveTask(selected, parent, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(moveUp);
    JMenuItem moveDown = new JMenuItem("Move Down");
    moveDown.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            int pos = Math.min(parent.getIndex(selected) + 1, parent.getChildCount() - 1);
            moveTask(selected, parent, pos);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(moveDown);
    JMenuItem moveBottom = new JMenuItem("Move to Bottom");
    moveBottom.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selected.getParent();
            moveTask(selected, parent, parent.getChildCount() - 1);
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(moveBottom);
    this.popup.add(new JSeparator());
    JMenuItem rename = new JMenuItem("Edit");
    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode selected = getSelectedNode();
            String newText = prompt((String) selected.getUserObject());
            if (newText != null && newText.length() > 0) {
                selected.setUserObject(newText);
                Main.this.taskTree.getTreeModel().reload(selected);
                try {
                    Main.this.taskTree.changesMade();
                } catch (Exception ex) {
                    error(ex.getMessage());
                }
            }
        }
    });
    this.popup.add(rename);
    JMenuItem delete = new JMenuItem("Delete");
    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            promptAndRemove(getSelectedNode());
            try {
                Main.this.taskTree.changesMade();
            } catch (Exception ex) {
                error(ex.getMessage());
            }
        }
    });
    this.popup.add(delete);

    this.setVisible(true);

    loadConfig();
    load();

    syncButton.setVisible(this.taskTree.hasSyncCapability());
}

From source file:edu.brown.gui.CatalogViewer.java

protected void highlight(Collection<DefaultMutableTreeNode> nodes) {
    // Collapse everything and then show the paths to each node
    for (int ctr = this.catalogTree.getRowCount(); ctr >= 0; ctr--) {
        if (this.catalogTree.isExpanded(ctr)) {
            this.catalogTree.collapseRow(ctr);
        }//  www .j  ava  2 s . c o  m
    } // FOR
    this.catalogTree.getSelectionModel().clearSelection();

    for (DefaultMutableTreeNode node : nodes) {
        TreePath path = new TreePath(node.getPath());
        this.catalogTree.setSelectionPath(path);
        this.catalogTree.expandPath(path);
    } // FOR
}

From source file:com.openbravo.pos.admin.RolesViewTree.java

private void createTree() {

    //Create the jtree            
    root = new DefaultMutableTreeNode();
    uTree = new CheckboxTree(root);
    root.setUserObject("All Permissions");
    uTree.getCheckingModel().setCheckingMode(TreeCheckingModel.CheckingMode.PROPAGATE_PRESERVING_CHECK);
    uTree.clearSelection();/* w  w w  . java 2s.c  o m*/

    DefaultCheckboxTreeCellRenderer renderer = (DefaultCheckboxTreeCellRenderer) uTree.getCellRenderer();
    renderer.setLeafIcon(null);
    renderer.setClosedIcon(null);
    renderer.setOpenIcon(null);

    // set up listeners
    MouseListener ml = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            int selRow = uTree.getRowForLocation(e.getX(), e.getY());
            TreePath selPath = uTree.getPathForLocation(e.getX(), e.getY());

            if (selPath != null) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
                // If using Right to left Language change the way the check tree works    
                if (!uTree.getComponentOrientation().isLeftToRight()) {
                    if (uTree.isPathChecked(new TreePath(node.getPath()))) {
                        uTree.removeCheckingPath(new TreePath(node.getPath()));
                    } else {
                        uTree.addCheckingPath(new TreePath(node.getPath()));
                    }
                }
                jPermissionDesc.setText(descriptionMap.get(node));
            }
        }
    };
    uTree.addMouseListener(ml);

    // when this listener is fired changes state to dirty 
    uTree.addTreeCheckingListener(new TreeCheckingListener() {
        public void valueChanged(TreeCheckingEvent e) {
            passedDirty.setDirty(true);
        }
    });

    try {
        // Get list of all the permisions in the database
        // and the list of sections
        dbPermissions = (List) m_dlAdmin.getAlldbPermissions();
        branches = m_dlAdmin.getSectionsList();
    } catch (BasicException ex) {
        Logger.getLogger(RolesViewTree.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Create the main branches in the tree
    for (Object branch : branches) {
        section = ((StringUtils.substring(branch.toString(), 0, 2)).equals("##"))
                ? AppLocal.getIntString(StringUtils.right(branch.toString(), branch.toString().length() - 2))
                : branch.toString();
        root.add(new DefaultMutableTreeNode(section));
    }

    classMap = new HashMap();
    descriptionMap = new HashMap();
    nodePaths = new HashMap();
    // Replace displayname, Section and Description 
    // from the database with the correct details from the permissions locale        
    for (DBPermissionsInfo Perm : dbPermissions) {
        Perm.setDisplayName(((StringUtils.substring(Perm.getDisplayName(), 0, 2)).equals("##"))
                ? AppLocal.getIntString(
                        StringUtils.right(Perm.getDisplayName(), Perm.getDisplayName().length() - 2))
                : Perm.getDisplayName());
        Perm.setSection(((StringUtils.substring(Perm.getSection(), 0, 2)).equals("##"))
                ? AppLocal.getIntString(StringUtils.right(Perm.getSection(), Perm.getSection().length() - 2))
                : Perm.getSection());
        Perm.setDescription(((StringUtils.substring(Perm.getDescription(), 0, 2)).equals("##"))
                ? AppLocal.getIntString(
                        StringUtils.right(Perm.getDescription(), Perm.getDescription().length() - 2))
                : Perm.getDescription());
    }
    //put the list into order by display name
    sort();
    // Create the leaf nodes & fill in hashmap's
    for (DBPermissionsInfo Perm : dbPermissions) {
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(Perm.getDisplayName(), false);
        if (searchNode(Perm.getSection(), root) != null) {
            searchNode(Perm.getSection(), root).add(newNode);
            classMap.put("[All Permissions, " + Perm.getSection() + ", " + newNode + "]", Perm.getClassName());
            descriptionMap.put(newNode, Perm.getDescription());
            nodePaths.put(Perm.getClassName(), newNode);
        }
    }
    root = sortTree(root);
    jScrollPane1.setViewportView(uTree);
    uTree.expandAll();
}

From source file:edu.ku.brc.specify.tasks.subpane.security.NavigationTreeContextMenuMgr.java

/**
 * @param node/* ww w .j  a  v a2  s. co  m*/
 */
private void addToAdminGroup(final DefaultMutableTreeNode node) {
    if (node != null) {
        Object userObject = node.getUserObject();
        if (userObject != null) {
            FormDataObjIFace dmObject = ((DataModelObjBaseWrapper) userObject).getDataObj();
            if (dmObject != null && dmObject instanceof SpecifyUser) {
                SpPrincipal adminPrin = null;
                DataProviderSessionIFace session = null;
                try {
                    session = DataProviderFactory.getInstance().createSession();
                    adminPrin = (SpPrincipal) session.getData(SpPrincipal.class, "name", "Administrator",
                            DataProviderSessionIFace.CompareType.Equals);
                    if (adminPrin != null) {
                        SpecifyUser spUser = session.get(SpecifyUser.class, ((SpecifyUser) dmObject).getId());
                        spUser.addUserToSpPrincipalGroup(adminPrin);

                        session.beginTransaction();
                        session.saveOrUpdate(spUser);
                        session.saveOrUpdate(adminPrin);
                        session.commit();

                        DefaultMutableTreeNode adminNode = getAdminTreeNode(
                                (DefaultMutableTreeNode) treeMgr.getTree().getModel().getRoot());
                        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(
                                new DataModelObjBaseWrapper(spUser));

                        DefaultTreeModel model = (DefaultTreeModel) getTree().getModel();
                        model.insertNodeInto(newNode, adminNode, adminNode.getChildCount());
                        model.nodeChanged(adminNode);
                        model.nodeChanged(newNode);
                        getTree().repaint();

                        getTree().setSelectionPath(new TreePath(newNode.getPath()));

                        lastClickComp = null;
                        updateBtnUI();
                    }

                } catch (final Exception e1) {
                    e1.printStackTrace();

                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(NavigationTreeMgr.class, e1);
                    session.rollback();

                } finally {
                    if (session != null) {
                        session.close();
                    }
                }
            }
        }
    }
}

From source file:com.mindcognition.mindraider.ui.swing.trash.TrashJPanel.java

/**
 * Add an child object to a parent object.
 *
 * @param parent//from   w ww.j a  va 2 s .  c o  m
 *            the parent object.
 * @param child
 *            the child object.
 * @param shouldBeVisible
 *            if <code>true</code> the object should be visible.
 * @return Returns a <code>DefaultMutableTreeNode</code>
 */
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible) {
    DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);

    if (parent == null) {
        parent = rootNode;
    }

    treeModel.insertNodeInto(childNode, parent, parent.getChildCount());

    // Make sure the user can see the lovely new node.
    if (shouldBeVisible) {
        tree.scrollPathToVisible(new TreePath(childNode.getPath()));
    }
    return childNode;
}

From source file:de.rub.syssec.saaf.gui.editor.FileTree.java

public DefaultMutableTreeNode searchNode(String nodeStr, String lineNr) {

    DefaultMutableTreeNode node = null;
    @SuppressWarnings("unchecked")
    Enumeration<DefaultMutableTreeNode> e = ((DefaultMutableTreeNode) fileTree.getModel().getRoot())
            .breadthFirstEnumeration();/*from  w w w  .  j av  a  2 s  .c  o m*/

    while (e.hasMoreElements()) {

        node = (DefaultMutableTreeNode) e.nextElement();
        String filepath = "";

        for (int i = 0; i < node.getPath().length; i++) {
            filepath = filepath + File.separator + node.getPath()[i];
        }
        if (filepath.startsWith(nodeStr)) {
            TreeNode[] nodes = node.getPath();
            TreePath path = new TreePath(nodes);
            fileTree.scrollPathToVisible(path);
            fileTree.setSelectionPath(path);
            if (lineNr != null) {
                try {
                    editor.goToLine(Integer.parseInt(lineNr));
                } catch (Exception e1) {
                    logger.warn("Problem during tree construction", e1);
                }
            }

            return node;
        }

    }
    return null;
}

From source file:fr.jmmc.jmcs.logging.LogbackGui.java

private void jButtonExpandActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExpandActionPerformed
    final DefaultMutableTreeNode currentNode = getTreeLoggers().findTreeNode(_currentLogger);
    getTreeLoggers().expandAll(new TreePath(currentNode.getPath()), true,
            (currentNode == getTreeLoggers().getRootNode()) ? false : true);
}