Example usage for javax.swing.tree TreePath getPath

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

Introduction

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

Prototype

public Object[] getPath() 

Source Link

Document

Returns an ordered array of the elements of this TreePath .

Usage

From source file:de.erdesignerng.visual.common.OutlineComponent.java

/**
 * Refresh the model tree as there were changes.
 *
 * @param aModel - model/*w w w  . ja va2  s  .  c o m*/
 */
public void refresh(Model aModel) {

    if (aModel != null) {

        TreePath theSelected = tree.getSelectionPath();

        DefaultMutableTreeNode theGroup = null;
        DefaultMutableTreeNode theSelectedNode = theSelected != null
                ? (DefaultMutableTreeNode) theSelected.getLastPathComponent()
                : null;
        if (theSelected != null && theSelected.getPathCount() > 1) {
            theGroup = (DefaultMutableTreeNode) theSelected.getPath()[1];
        }

        Set<Object> theExpandedUserObjects = expandedUserObjects;

        setModel(aModel);

        List<TreePath> thePathsToExpand = new ArrayList<>();
        TreePath theNewSelection = null;

        for (int theRow = 0; theRow < tree.getRowCount(); theRow++) {
            TreePath thePath = tree.getPathForRow(theRow);

            DefaultMutableTreeNode theLastNew = (DefaultMutableTreeNode) thePath.getLastPathComponent();
            if (theExpandedUserObjects.contains(theLastNew.getUserObject())) {
                thePathsToExpand.add(thePath);
            }
            if (theSelectedNode != null) {
                DefaultMutableTreeNode theLastGroup = null;
                if (thePath.getPathCount() > 1) {
                    theLastGroup = (DefaultMutableTreeNode) thePath.getPath()[1];
                }
                if (theLastGroup != null && theGroup != null) {
                    if (!theLastGroup.getUserObject().equals(theGroup.getUserObject())) {
                        continue;
                    }
                }
                if (theLastNew.getUserObject().equals(theSelectedNode.getUserObject())) {
                    theNewSelection = thePath;
                }
            }
        }

        thePathsToExpand.forEach(tree::expandPath);

        if (theNewSelection != null) {
            tree.setSelectionPath(theNewSelection);
            tree.scrollPathToVisible(theNewSelection);
        }
    }
}

From source file:dataviewer.DataViewer.java

/**
 * Creates new form DataViewer/*w w w. j  a va 2s. c  o  m*/
 */
public DataViewer() {
    try {
        for (Enum ee : THREAD.values()) {
            t[ee.ordinal()] = new Thread();
        }
        initComponents();
        DropTarget dropTarget = new DropTarget(tr_files, new DropTargetListenerImpl());
        TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {
                javax.swing.JTree tree = (javax.swing.JTree) e.getSource();
                TreePath path = tree.getSelectionPath();
                Object[] pnode = (Object[]) path.getPath();
                String name = pnode[pnode.length - 1].toString();
                String ex = getExtension(name);
                if (ex.equals(".txt") || ex.equals(".dat") || ex.equals(".csv") || ex.equals(".tsv")) {
                    selected_file = name;
                } else {
                    selected_file = "";
                }
            }
        };
        tr_files.addTreeSelectionListener(treeSelectionListener);

        tr_files.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() >= 2) {
                    if (!"".equals(selected_file)) {
                        //count_data();
                        read_data();
                    } else {
                        TreePath path = tr_files.getSelectionPath();
                        if (path.getLastPathComponent().toString().equals(cur_path)) {
                            cur_path = (new File(cur_path)).getParent();
                        } else {
                            cur_path = cur_path + File.separator + path.getLastPathComponent().toString();
                        }
                        fill_tree();
                    }
                }
            }
        });

        tr_files.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                    cur_path = (new File(cur_path)).getParent();
                    fill_tree();
                } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (!"".equals(selected_file)) {
                        //count_data();
                        read_data();
                    } else {
                        TreePath path = tr_files.getSelectionPath();
                        if (path.getLastPathComponent().toString().equals(cur_path)) {
                            cur_path = (new File(cur_path)).getParent();
                        } else {
                            cur_path = cur_path + File.separator + path.getLastPathComponent().toString();
                        }
                        fill_tree();
                    }
                } else if (evt.getKeyCode() == KeyEvent.VK_DELETE) {

                    if (!"".equals(selected_file)) {
                        String name = cur_path + File.separator + selected_file;
                        if ((new File(name)).isFile()) {
                            int dialogResult = JOptionPane.showConfirmDialog(null,
                                    "Selected file [" + selected_file
                                            + "] will be removed and not recoverable.",
                                    "Are you sure?", JOptionPane.YES_NO_OPTION);
                            if (dialogResult == JOptionPane.YES_OPTION) {
                                (new File(name)).delete();
                                fill_tree();
                            }
                        }

                    } else {
                        JOptionPane.showMessageDialog(null,
                                "For safety concern, removing folder is not supported.", "Information",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        tr_files.setCellRenderer(new MyTreeCellRenderer());
        p_count.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

        //tp_menu.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ctrl1, "tab_read");
        //tp_menu.getActionMap().put("tab_read", (Action) new ActionListenerImpl());
        //tp_menu.setMnemonicAt(0, KeyEvent.VK_1);
        //tp_menu.setMnemonicAt(1, KeyEvent.VK_2);
        /*InputMap inputMap = tp_menu.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
         ActionMap actionMap = tp_menu.getActionMap();
                
         KeyStroke ctrl1 = KeyStroke.getKeyStroke("ctrl 1");
         inputMap.put(ctrl1, "tab_read");
         actionMap.put("tab_read", new AbstractAction() {
                
         @Override
         public void actionPerformed(ActionEvent arg0) {
         tp_menu.setSelectedIndex(0);
         }
         });
                
         KeyStroke ctrl2 = KeyStroke.getKeyStroke("ctrl 2");
         inputMap.put(ctrl2, "tab_analyze");
         actionMap.put("tab_analyze", new AbstractAction() {
                
         @Override
         public void actionPerformed(ActionEvent arg0) {
         tp_menu.setSelectedIndex(1);
         }
         });*/
        config();
    } catch (Exception e) {
        txt_count.setText(e.getMessage());
    }
}

From source file:edu.ku.brc.af.tasks.subpane.formeditor.ViewSetSelectorPanel.java

/**
 * @param selectedControl/* w w w .ja v a  2s .c  om*/
 * @param selectedCell
 */
protected void addControl(final ControlIFace selectedControl,
        @SuppressWarnings("hiding") final FormCell selectedCell) {
    int position = 0;
    if (selectedCell != null) {
        position = selectedRow.getCells().indexOf(selectedCell);
    }

    if (selectedControl instanceof RowControl) {
        addRow();
        return;
    }

    @SuppressWarnings("hiding")
    EditorPropPanel panel = new EditorPropPanel(controlHash, subcontrolHash, getAvailableFieldCells(), false,
            this);
    //panel.setFormViewDef(formViewDef);

    FormCell formCell = null;
    boolean skip = false;
    if (selectedControl instanceof Control) {
        Control control = (Control) selectedControl;

        if (control.getType().equals("label")) //$NON-NLS-1$
        {
            formCell = new FormCellLabel();
            formCell.setIdent(Integer.toString(getNextId()));
        }

        if (formCell != null) {
            formCell.setType(FormCellIFace.CellType.valueOf(control.getType()));

            //System.out.println(formCell.getType() + "  "+ formCell.getClass().getSimpleName());

            panel.loadView(formCell.getType().toString(), selectedViewDef.getClassName());
            panel.setDataIntoUI(formViewDef, formCell, (formViewDef.getRows().size() * 2) - 1,
                    formViewDef.getRowDefItem().getNumItems(), selectedRow.getRowNumber(),
                    (selectedRow.getCells().size() * 2) - 1, formViewDef.getColumnDefItem().getNumItems(),
                    position);
        }

    } else {
        SubControl subControl = (SubControl) selectedControl;

        FormCellField fcf = null;
        if (subControl.getType().equals("combobox")) //$NON-NLS-1$
        {
            fcf = new FormCellField(FormCell.CellType.field, Integer.toString(getNextId()), "", 1, 1); //$NON-NLS-1$
            fcf.setUiType(FormCellFieldIFace.FieldType.combobox);
            setDefaultDspUIType(fcf);
            formCell = fcf;
        }
        //System.out.println("* ["+fcf.getUiType().toString() + "]  "+ fcf.getClass().getSimpleName());
        //SubControl subcontrol = subcontrolHash.get(fcf.getUiType().toString());
        //System.out.println("SC: "+subcontrol);

        panel.loadView(fcf.getUiType().toString(), selectedViewDef.getClassName());
        panel.setDataIntoUI(formViewDef, fcf, (formViewDef.getRows().size() * 2) - 1,
                formViewDef.getRowDefItem().getNumItems(), selectedRow.getRowNumber(),
                (selectedRow.getCells().size() * 2) - 1, formViewDef.getColumnDefItem().getNumItems(),
                position);

    }

    if (!skip && formCell != null) {
        CustomDialog propDlg = new CustomDialog((Frame) UIRegistry.getTopWindow(),
                getResourceString("ViewSetSelectorPanel.CREATE"), true, panel); //$NON-NLS-1$
        propDlg.createUI();
        //panel.getViewDefMultiView().getCurrentView().getValidator().addEnableItem(propDlg.getOkBtn());
        propDlg.pack();
        Rectangle r = propDlg.getBounds();
        r.width += 60;
        r.height += 30;
        propDlg.setBounds(r);
        propDlg.setVisible(true);

        if (!propDlg.isCancelled()) {
            if (selectedControl instanceof Control) {
                panel.getDataFromUI(formCell);
            } else {
                panel.getDataFromUI((FormCellField) formCell);
            }

            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(formCell);
            newNode.setUserObject(formCell);

            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) tree.getSelectionModel()
                    .getSelectionPath().getLastPathComponent();
            if (!(parentNode.getUserObject() instanceof FormRow)) {
                parentNode = (DefaultMutableTreeNode) parentNode.getParent();
            }

            TreePath treePath = tree.getSelectionModel().getSelectionPath();
            Object[] path = treePath.getPath();

            Object[] newPath = new Object[path.length + (selectedCell == null ? 1 : 0)];
            for (int i = 0; i < path.length; i++) {
                newPath[i] = path[i];
            }
            newPath[newPath.length - 1] = newNode;

            if (selectedRow.getCells().size() == 0) {
                selectedRow.getCells().add(formCell);
                ((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, parentNode, 0);

            } else if (position == selectedRow.getCells().size() - 1) {
                //System.out.println("Adding New Cell at position["+(position+1)+"] number of nodes["+nodeParent.getChildCount()+"] rowCells "+selectedRow.getCells().size());
                selectedRow.getCells().add(formCell);
                ((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, parentNode, position + 1);

            } else {
                //System.out.println("Adding New Cell at position["+position+"] number of nodes["+nodeParent.getChildCount()+"] rowCells "+selectedRow.getCells().size());
                selectedRow.getCells().insertElementAt(formCell, position + 1);
                ((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, parentNode, position + 1);
            }

            //System.out.println("******* ADDING ["+formCell.getIdent()+"]"); //$NON-NLS-1$ //$NON-NLS-2$

            idHash.put(formCell.getIdent(), true);

            final TreePath newTreePath = new TreePath(newPath);
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    tree.setSelectionPath(newTreePath);
                }
            });

            previewPanel.rebuild(false);
        }
    }

}

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  w  ww . j  a v a  2 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: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/*  w w  w. j av  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:org.apache.cayenne.modeler.ProjectTreeView.java

private void initController() {
    treeSelectionListener = new TreeSelectionListener() {

        public void valueChanged(TreeSelectionEvent e) {
            TreePath[] paths = getSelectionPaths();

            if (paths != null) {
                if (paths.length > 1) {
                    ConfigurationNode projectParentPath = null;
                    ConfigurationNode[] projectPaths = new ConfigurationNode[paths.length];
                    boolean commonParentPath = true;

                    for (int i = 0; i < paths.length; i++) {
                        projectPaths[i] = createProjectPath(paths[i]);

                        TreePath parentPath = paths[i].getParentPath();
                        if (i > 0 && parentPath != null && !parentPath.equals(paths[i - 1].getParentPath())) {
                            commonParentPath = false;
                        }//  w w  w  .j av a2s .co m
                    }

                    if (commonParentPath) {
                        TreePath parentPath = paths[0].getParentPath();
                        projectParentPath = createProjectPath(parentPath);
                    }

                    mediator.fireMultipleObjectsDisplayEvent(
                            new MultipleObjectsDisplayEvent(this, projectPaths, projectParentPath));
                } else if (paths.length == 1) {
                    processSelection(paths[0]);
                }
            }
        }

        /**
         * Converts TreePath to Object
         */
        private ConfigurationNode createProjectPath(TreePath treePath) {
            Object[] path = treePath.getPath();
            ConfigurationNode projectPath = (ConfigurationNode) ((DefaultMutableTreeNode) path[path.length - 1])
                    .getUserObject();

            return projectPath;
        }
    };

    treeWillExpandListener = new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent e) throws ExpandVetoException {
            TreePath path = e.getPath();
            if (!isPathSelected(path) && !isSelectionEmpty()) {
                setSelectionPath(path);
            }
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent e) throws ExpandVetoException {
            TreePath path = e.getPath();
            if (!isPathSelected(path) && !isSelectionEmpty()) {
                setSelectionPath(path);
            }
        }
    };

    addTreeSelectionListener(treeSelectionListener);
    addTreeWillExpandListener(treeWillExpandListener);

    addMouseListener(new PopupHandler());

    mediator.addDomainListener(this);
    mediator.addDomainDisplayListener(this);
    mediator.addDataNodeListener(this);
    mediator.addDataNodeDisplayListener(this);
    mediator.addDataMapListener(this);
    mediator.addDataMapDisplayListener(this);
    mediator.addObjEntityListener(this);
    mediator.addObjEntityDisplayListener(this);
    mediator.addDbEntityListener(this);
    mediator.addDbEntityDisplayListener(this);
    mediator.addEmbeddableDisplayListener(this);
    mediator.addEmbeddableListener(this);
    mediator.addProcedureListener(this);
    mediator.addProcedureDisplayListener(this);
    mediator.addQueryListener(this);
    mediator.addQueryDisplayListener(this);
    mediator.addMultipleObjectsDisplayListener(this);

    mediator.getApplication().getActionManager().setupCutCopyPaste(this, CutAction.class, CopyAction.class);
}

From source file:org.domainmath.gui.FileTreePanel.java

/**
 * Confirm removal of contents from File Tree.
 * @param selectionPaths // w w w  . j av  a 2  s  .  c  om
 */
private void confirmDeletion(final TreePath[] selectionPaths) {
    final Delete confirmDialog = new Delete(frame);
    JButton yes = new JButton("Yes,Delete");
    JButton no = new JButton("No");
    confirmDialog.setSecondTitle("Are you sure to delete selected contents?");

    yes.addActionListener(new ActionListener() {
        Object[] path1;
        String s = "";

        @Override
        public void actionPerformed(ActionEvent e) {
            for (TreePath path : selectionPaths) {
                path1 = path.getPath();
                for (Object path11 : path1) {
                    s += path11 + File.separator;
                }
                delete(new File(s));
                s = "";
            }
            confirmDialog.dispose();
        }

    });

    no.addActionListener((ActionEvent e) -> {
        confirmDialog.dispose();
    });

    confirmDialog.addButton(yes);
    confirmDialog.addButton(no);
    confirmDialog.setVisible(true);
}

From source file:org.eclipse.jubula.rc.swing.tester.util.TreeOperationContext.java

/**
 * Calls/*from  w  w  w  . j  a v  a 2 s  .  c  o  m*/
 * {@link JTree#convertValueToText(java.lang.Object, boolean, boolean, boolean, int, boolean)}
 * on any tree node of the <code>treePath</code> and returns the texts as an array.
 * @param treePath The tree path
 * @return The array of converted texts
 */
protected String[] convertTreePathToText(Object treePath) {
    final TreePath tp = (TreePath) treePath;
    Object[] path = tp.getPath();
    String[] values = new String[path.length];
    for (int i = 0; i < path.length; i++) {
        values[i] = convertValueToText(path[i], getRowForTreeNode(path[i]));
    }
    return values;
}

From source file:org.hippoecm.frontend.plugins.cms.admin.updater.UpdaterPanel.java

private void expandAndSelectNodeInTree(final AjaxRequestTarget target) {
    final JcrNodeModel model = (JcrNodeModel) getDefaultModel();
    final TreePath treePath = treeModel.lookup(model);
    final ITreeState treeState = tree.getTreeState();
    for (Object n : treePath.getPath()) {
        final TreeNode treeNode = (TreeNode) n;
        if (!treeState.isNodeExpanded(treeNode)) {
            treeState.expandNode(treeNode);
        }/*from ww  w  .  j a  v  a  2  s . c  o m*/
    }
    treeState.selectNode(treePath.getLastPathComponent(), true);
    tree.updateTree(target);
}

From source file:org.hippoecm.frontend.plugins.cms.browse.tree.FolderTreePlugin.java

@Override
public void onModelChanged() {
    super.onModelChanged();

    if (tree == null) {
        return;//  w w w .jav a 2s.  c  o m
    }
    JcrNodeModel model = (JcrNodeModel) getDefaultModel();
    ITreeState treeState = tree.getTreeState();
    TreePath treePath = treeModel.lookup(model);
    if (treePath != null) {
        for (Object component : treePath.getPath()) {
            TreeNode treeNode = (TreeNode) component;
            if (!treeState.isNodeExpanded(treeNode)) {
                treeState.expandNode(treeNode);
            }
        }
        treeState.selectNode(treePath.getLastPathComponent(), true);
    }
}