Example usage for javax.swing.tree TreePath getPathCount

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

Introduction

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

Prototype

public int getPathCount() 

Source Link

Document

Returns the number of elements in the path.

Usage

From source file:MainClass.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Traverse Tree");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTree tree = new JTree();
    tree.setRootVisible(true);/* w  ww  .j  a  va  2s.  co m*/
    TreeModel model = tree.getModel();
    Object rootObject = model.getRoot();
    if ((rootObject != null) && (rootObject instanceof DefaultMutableTreeNode)) {
        DefaultMutableTreeNode r = (DefaultMutableTreeNode) rootObject;
        printDescendents(r);
        Enumeration breadth = r.breadthFirstEnumeration();
        Enumeration depth = r.depthFirstEnumeration();
        Enumeration preOrder = r.preorderEnumeration();
        printEnumeration(breadth, "Breadth");
        printEnumeration(depth, "Depth");
        printEnumeration(preOrder, "Pre");
    }

    TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
            JTree treeSource = (JTree) treeSelectionEvent.getSource();
            TreePath path = treeSource.getSelectionPath();
            System.out.println(path);
            System.out.println(path.getPath());
            System.out.println(path.getParentPath());
            System.out.println(((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject());
            System.out.println(path.getPathCount());
        }
    };
    tree.addTreeSelectionListener(treeSelectionListener);

    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 400);
    frame.setVisible(true);
}

From source file:Main.java

/**
 * @return true, if path1 is a descendant of path2. Else, returns false.
 *//*from  ww w . java  2 s.  co  m*/
public static boolean isDescendant(TreePath path1, TreePath path2) {
    int count1 = path1.getPathCount();
    int count2 = path2.getPathCount();
    if (count1 <= count2)
        return false;
    while (count1 != count2) {
        path1 = path1.getParentPath();
        count1--;
    }
    return path1.equals(path2);
}

From source file:Main.java

public static String getNameNodoAtIndex(int ind, JTree jtree) {

    TreePath parentPath = jtree.getSelectionPath();

    int level = 0;

    if (parentPath != null) {

        level = parentPath.getPathCount();
    }/*from  w w w  .jav  a 2  s. co m*/

    return "" + parentPath.getPathComponent(ind);
}

From source file:org.schreibubi.JCombinations.ui.GridChartPanel.java

/**
 * Create PDF//  w w w .j av  a  2 s . c  o m
 * 
 * @param name
 *            Filename
 * @param selection
 *            Selected Nodes
 * @param dm
 *            DataModel
 * @param pl
 *            ProgressListener
 */
@SuppressWarnings("unchecked")
public static void generatePDF(File name, DataModel dm, ArrayList<TreePath> selection, ProgressListener pl) {
    com.lowagie.text.Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
    try {
        ArrayList<ExtendedJFreeChart> charts = dm.getCharts(selection);
        if (charts.size() > 0) {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name));
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
            document.addAuthor("Jrg Werner");
            document.addSubject("Created by JCombinations");
            document.addKeywords("JCombinations");
            document.addCreator("JCombinations using iText");

            // we define a header and a footer
            HeaderFooter header = new HeaderFooter(new Phrase("JCombinations by Jrg Werner"), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));
            footer.setAlignment(Element.ALIGN_CENTER);
            document.setHeader(header);
            document.setFooter(footer);

            document.open();
            DefaultFontMapper mapper = new DefaultFontMapper();
            FontFactory.registerDirectories();
            mapper.insertDirectory("c:\\WINNT\\fonts");

            PdfContentByte cb = writer.getDirectContent();

            pl.progressStarted(new ProgressEvent(GridChartPanel.class, 0, charts.size()));
            for (int i = 0; i < charts.size(); i++) {
                ExtendedJFreeChart chart = charts.get(i);
                PdfTemplate tp = cb.createTemplate(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                Graphics2D g2d = tp.createGraphics(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN), mapper);
                Rectangle2D r2d = new Rectangle2D.Double(0, 0,
                        document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                chart.draw(g2d, r2d);
                g2d.dispose();
                cb.addTemplate(tp, document.left(EXTRA_MARGIN), document.bottom(EXTRA_MARGIN));
                PdfDestination destination = new PdfDestination(PdfDestination.FIT);
                TreePath treePath = chart.getTreePath();
                PdfOutline po = cb.getRootOutline();
                for (int j = 0; j < treePath.getPathCount(); j++) {
                    ArrayList<PdfOutline> lpo = po.getKids();
                    PdfOutline cpo = null;
                    for (PdfOutline outline : lpo)
                        if (outline.getTitle().compareTo(treePath.getPathComponent(j).toString()) == 0)
                            cpo = outline;
                    if (cpo == null)
                        cpo = new PdfOutline(po, destination, treePath.getPathComponent(j).toString());
                    po = cpo;
                }
                document.newPage();
                pl.progressIncremented(new ProgressEvent(GridChartPanel.class, i));
            }
            document.close();
            pl.progressEnded(new ProgressEvent(GridChartPanel.class));

        }
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:Main.java

private boolean canPathBeAdded(TreePath treePath) {
    return treePath.getPathCount() > 2;
}

From source file:TreeDragTest.java

public void dragGestureRecognized(DragGestureEvent dge) {
    TreePath path = sourceTree.getSelectionPath();
    if ((path == null) || (path.getPathCount() <= 1)) {
        // We can't move the root node or an empty selection
        return;//from  w  w w.  j  av a2s .c  om
    }
    oldNode = (DefaultMutableTreeNode) path.getLastPathComponent();
    transferable = new TransferableTreeNode(path);
    source.startDrag(dge, DragSource.DefaultMoveNoDrop, transferable, this);

    // If you support dropping the node anywhere, you should probably
    // start with a valid move cursor:
    //source.startDrag(dge, DragSource.DefaultMoveDrop, transferable,
    // this);
}

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

protected DefaultMutableTreeNode getSelectedNode() {
    int[] selected = tree.getSelectionRows();
    if (selected == null || selected.length == 0) {
        return null;
    }/*from w  w  w  .ja va 2s.co m*/
    TreePath path = tree.getPathForRow(selected[0]);
    if (path == null || path.getPathCount() == 0) {
        return null;
    }
    return (DefaultMutableTreeNode) path.getLastPathComponent();
}

From source file:de.codesourcery.eve.skills.ui.components.impl.BlueprintChooserComponent.java

public Blueprint getCurrentlySelectedBlueprint() {
    final TreePath path = tree.getSelectionPath();
    if (path != null && path.getPathCount() > 0) {
        return getSelectedBlueprint((ITreeNode) path.getLastPathComponent());
    }/*www .  j  a  v  a2 s .c o  m*/
    return null;
}

From source file:de.codesourcery.eve.skills.ui.components.impl.ItemBrowserComponent.java

@Override
protected JPanel createPanel() {

    final JPanel result = new JPanel();
    result.setLayout(new GridBagLayout());

    treeModelBuilder = new MarketGroupTreeModelBuilder(dataModel);

    treeModelBuilder.attach(itemTree);// w w  w.  ja  v a2  s.  c om

    itemTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            if (e.getPath() != null) {
                treeSelectionChanged((ITreeNode) e.getPath().getLastPathComponent());
            } else {
                treeSelectionChanged(null);
            }
        }
    });

    itemTree.setCellRenderer(new DefaultTreeCellRenderer() {
        public java.awt.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);
            final ITreeNode node = (ITreeNode) value;
            if (node.getValue() instanceof MarketGroup) {
                setText(((MarketGroup) node.getValue()).getName());
            } else if (node.getValue() instanceof InventoryType) {
                setText(((InventoryType) node.getValue()).getName());
            }
            return this;
        };
    });

    // text area
    itemDetails.setLineWrap(true);
    itemDetails.setWrapStyleWord(true);
    itemDetails.setEditable(false);

    // context menu
    final PopupMenuBuilder menuBuilder = new PopupMenuBuilder();
    menuBuilder.addItem("Refine...", new AbstractAction() {

        @Override
        public boolean isEnabled() {
            return getSelectedType() != null && selectionProvider.getSelectedItem() != null;
        }

        private InventoryType getSelectedType() {
            final TreePath selection = itemTree.getSelectionPath();
            if (selection != null && selection.getPathCount() > 0) {
                final ITreeNode node = (ITreeNode) selection.getLastPathComponent();
                if (node.getValue() instanceof InventoryType) {
                    return (InventoryType) node.getValue();
                }
            }
            return null;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            final ICharacter currentCharacter = selectionProvider.getSelectedItem();
            final InventoryType t = getSelectedType();
            if (t != null && currentCharacter != null) {

                final RefiningComponent comp = new RefiningComponent(currentCharacter);
                comp.setModal(true);
                comp.setItemsToRefine(Collections.singletonList(new ItemWithQuantity(getSelectedType(), 1)));
                ComponentWrapper.wrapComponent(comp).setVisible(true);
            }

        }
    });
    menuBuilder.attach(itemTree);

    result.add(new JScrollPane(itemTree), constraints(0, 0).resizeBoth().end());
    result.add(new JScrollPane(itemDetails), constraints(1, 0).resizeBoth().end());
    return result;
}

From source file:net.pms.newgui.SelectRenderers.java

/**
 * Create the GUI and show it./*  w  w w  .  j av a2s .  co  m*/
 */
public void showDialog() {
    if (!init) {
        // Initial call
        build();
        init = true;
    }
    SrvTree.validate();
    // Refresh setting if modified
    selectedRenderers = configuration.getSelectedRenderers();
    TreePath root = new TreePath(allRenderers);
    if (selectedRenderers.isEmpty() || (selectedRenderers.size() == 1 && selectedRenderers.get(0) == null)) {
        checkTreeManager.getSelectionModel().clearSelection();
    } else if (selectedRenderers.size() == 1 && selectedRenderers.get(0).equals(allRenderersTreeName)) {
        checkTreeManager.getSelectionModel().setSelectionPath(root);
    } else {
        if (root.getLastPathComponent() instanceof SearchableMutableTreeNode) {
            SearchableMutableTreeNode rootNode = (SearchableMutableTreeNode) root.getLastPathComponent();
            SearchableMutableTreeNode node = null;
            List<TreePath> selectedRenderersPath = new ArrayList<>(selectedRenderers.size());
            for (String selectedRenderer : selectedRenderers) {
                try {
                    node = rootNode.findInBranch(selectedRenderer, true);
                } catch (IllegalChildException e) {
                }
                if (node != null) {
                    selectedRenderersPath.add(new TreePath(node.getPath()));
                }
            }
            checkTreeManager.getSelectionModel().setSelectionPaths(
                    selectedRenderersPath.toArray(new TreePath[selectedRenderersPath.size()]));
        } else {
            LOGGER.error("Illegal node class in SelectRenderers.showDialog(): {}",
                    root.getLastPathComponent().getClass().getSimpleName());
        }
    }

    int selectRenderers = JOptionPane.showOptionDialog((Component) PMS.get().getFrame(), this,
            Messages.getString("GeneralTab.5"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null,
            null, null);

    if (selectRenderers == JOptionPane.OK_OPTION) {
        TreePath[] selected = checkTreeManager.getSelectionModel().getSelectionPaths();
        if (selected.length == 0) {
            if (configuration.setSelectedRenderers("")) {
                PMS.get().getFrame().setReloadable(true); // notify the user to restart the server
            }
        } else if (selected.length == 1
                && selected[0].getLastPathComponent() instanceof SearchableMutableTreeNode
                && ((SearchableMutableTreeNode) selected[0].getLastPathComponent()).getNodeName()
                        .equals(allRenderers.getNodeName())) {
            if (configuration.setSelectedRenderers(allRenderersTreeName)) {
                PMS.get().getFrame().setReloadable(true); // notify the user to restart the server
            }
        } else {
            List<String> selectedRenderers = new ArrayList<>();
            for (TreePath path : selected) {
                String rendererName = "";
                if (path.getPathComponent(0).equals(allRenderers)) {
                    for (int i = 1; i < path.getPathCount(); i++) {
                        if (path.getPathComponent(i) instanceof SearchableMutableTreeNode) {
                            if (!rendererName.isEmpty()) {
                                rendererName += " ";
                            }
                            rendererName += ((SearchableMutableTreeNode) path.getPathComponent(i))
                                    .getNodeName();
                        } else {
                            LOGGER.error("Invalid tree node component class {}",
                                    path.getPathComponent(i).getClass().getSimpleName());
                        }
                    }
                    if (!rendererName.isEmpty()) {
                        selectedRenderers.add(rendererName);
                    }
                } else {
                    LOGGER.warn("Invalid renderer treepath encountered: {}", path.toString());
                }
            }
            if (configuration.setSelectedRenderers(selectedRenderers)) {
                PMS.get().getFrame().setReloadable(true); // notify the user to restart the server
            }
        }
    }
}