Example usage for javax.swing.tree TreePath getLastPathComponent

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

Introduction

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

Prototype

public Object getLastPathComponent() 

Source Link

Document

Returns the last element of this path.

Usage

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

/**
 * Create the GUI and show it./*from   www .  ja v  a 2  s. c  o 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
            }
        }
    }
}

From source file:gov.sandia.umf.platform.ui.jobs.RunPanel.java

public RunPanel() {
    root = new NodeBase();
    model = new DefaultTreeModel(root);
    tree = new JTree(model);
    tree.setRootVisible(false);/*from w  ww .  j  a  va 2s.  c om*/
    tree.setShowsRootHandles(true);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);

    tree.setCellRenderer(new DefaultTreeCellRenderer() {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

            NodeBase node = (NodeBase) value;
            Icon icon = node.getIcon(expanded); // A node knows whether it should hold other nodes or not, so don't pass leaf to it.
            if (icon == null) {
                if (leaf)
                    icon = getDefaultLeafIcon();
                else if (expanded)
                    icon = getDefaultOpenIcon();
                else
                    icon = getDefaultClosedIcon();
            }
            setIcon(icon);

            return this;
        }
    });

    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            NodeBase newNode = (NodeBase) tree.getLastSelectedPathComponent();
            if (newNode == null)
                return;
            if (newNode == displayNode)
                return;

            if (displayThread != null)
                synchronized (displayText) {
                    displayThread.stop = true;
                }
            displayNode = newNode;
            if (displayNode instanceof NodeFile)
                viewFile();
            else if (displayNode instanceof NodeJob)
                viewJob();
        }
    });

    tree.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            int keycode = e.getKeyCode();
            if (keycode == KeyEvent.VK_DELETE || keycode == KeyEvent.VK_BACK_SPACE) {
                delete();
            }
        }
    });

    tree.addTreeWillExpandListener(new TreeWillExpandListener() {
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            TreePath path = event.getPath(); // TODO: can this ever be null?
            Object o = path.getLastPathComponent();
            if (o instanceof NodeJob)
                ((NodeJob) o).build(tree);
        }

        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
        }
    });

    tree.addTreeExpansionListener(new TreeExpansionListener() {
        public void treeExpanded(TreeExpansionEvent event) {
            Rectangle node = tree.getPathBounds(event.getPath());
            Rectangle visible = treePane.getViewport().getViewRect();
            visible.height -= node.y - visible.y;
            visible.y = node.y;
            tree.repaint(visible);
        }

        public void treeCollapsed(TreeExpansionEvent event) {
            Rectangle node = tree.getPathBounds(event.getPath());
            Rectangle visible = treePane.getViewport().getViewRect();
            visible.height -= node.y - visible.y;
            visible.y = node.y;
            tree.repaint(visible);
        }
    });

    Thread refreshThread = new Thread() {
        public void run() {
            try {
                // Initial load
                synchronized (running) {
                    for (MNode n : AppData.runs)
                        running.add(0, new NodeJob(n)); // This should be efficient on a doubly-linked list.
                    for (NodeJob job : running)
                        root.add(job);
                }
                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        model.nodeStructureChanged(root);
                        if (model.getChildCount(root) > 0)
                            tree.setSelectionRow(0);
                    }
                });

                // Periodic refresh to show status of running jobs
                int shortCycles = 100; // Force full scan on first cycle.
                while (true) {
                    NodeBase d = displayNode; // Make local copy (atomic action) to prevent it changing from under us
                    if (d instanceof NodeJob)
                        ((NodeJob) d).monitorProgress(RunPanel.this);
                    if (shortCycles++ < 20) {
                        Thread.sleep(1000);
                        continue;
                    }
                    shortCycles = 0;

                    synchronized (running) {
                        Iterator<NodeJob> i = running.iterator();
                        while (i.hasNext()) {
                            NodeJob job = i.next();
                            if (job != d)
                                job.monitorProgress(RunPanel.this);
                            if (job.complete >= 1)
                                i.remove();
                        }
                    }
                }
            } catch (InterruptedException e) {
            }
        }
    };
    refreshThread.setDaemon(true);
    refreshThread.start();

    displayText = new JTextArea();
    displayText.setEditable(false);

    final JCheckBox chkFixedWidth = new JCheckBox("Fixed-Width Font");
    chkFixedWidth.setFocusable(false);
    chkFixedWidth.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int size = displayText.getFont().getSize();
            if (chkFixedWidth.isSelected()) {
                displayText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, size));
            } else {
                displayText.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, size));
            }
        }
    });

    displayPane.setViewportView(displayText);

    ActionListener graphListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (displayNode instanceof NodeFile) {
                NodeFile nf = (NodeFile) displayNode;
                if (nf.type == NodeFile.Type.Output || nf.type == NodeFile.Type.Result) {
                    String graphType = e.getActionCommand();
                    if (displayPane.getViewport().getView() instanceof ChartPanel
                            && displayGraph.equals(graphType)) {
                        viewFile();
                        displayGraph = "";
                    } else {
                        if (graphType.equals("Graph")) {
                            Plot plot = new Plot(nf.path.getAbsolutePath());
                            if (!plot.columns.isEmpty())
                                displayPane.setViewportView(plot.createGraphPanel());
                        } else // Raster
                        {
                            Raster raster = new Raster(nf.path.getAbsolutePath(), displayPane.getHeight());
                            displayPane.setViewportView(raster.createGraphPanel());
                        }
                        displayGraph = graphType;
                    }
                }
            }
        }
    };

    buttonGraph = new JButton("Graph", ImageUtil.getImage("analysis.gif"));
    buttonGraph.setFocusable(false);
    buttonGraph.addActionListener(graphListener);
    buttonGraph.setActionCommand("Graph");

    buttonRaster = new JButton("Raster", ImageUtil.getImage("prnplot.gif"));
    buttonRaster.setFocusable(false);
    buttonRaster.addActionListener(graphListener);
    buttonRaster.setActionCommand("Raster");

    Lay.BLtg(this, "C",
            Lay.SPL(Lay.BL("C", treePane = Lay.sp(tree)), Lay.BL("N",
                    Lay.FL(chkFixedWidth, Lay.FL(buttonGraph, buttonRaster), "hgap=50"), "C", displayPane),
                    "divpixel=250"));
    setFocusCycleRoot(true);
}

From source file:com.enderville.enderinstaller.ui.Installer.java

@Override
public void valueChanged(TreeSelectionEvent e) {
    if (!e.isAddedPath()) {
        return;//from   w  w w  . j a v  a 2s.com
    }
    TreePath path = e.getPath();
    CheckBoxTree tree = getModTree();
    if (e.getSource() == tree.getSelectionModel()) {
        DefaultMutableTreeNode last = (DefaultMutableTreeNode) path.getLastPathComponent();
        loadModDescription(last.getUserObject().toString());
    } else if (e.getSource() == tree.getCheckBoxTreeSelectionModel()) {
        getPresetDropdown().setSelectedItem(PRESET_CUSTOM);
    }
}

From source file:dotaSoundEditor.Controls.EditorPanel.java

protected void playSelectedTreeSound(TreePath selPath, Path vpkToPlayFrom) {
    try {/*  w  ww  .j av  a2  s. c o m*/
        DefaultMutableTreeNode selectedFile = ((DefaultMutableTreeNode) selPath.getLastPathComponent());
        String waveString = selectedFile.getUserObject().toString();
        File soundFile = createSoundFileFromWaveString(waveString, vpkToPlayFrom);
        soundPlayer.loadSound(soundFile.getAbsolutePath());
        soundPlayer.playSound();
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "The selected node does not represent a valid sound file.", "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:dotaSoundEditor.Controls.EditorPanel.java

protected void attachDoubleClickListenerToTree() {
    MouseListener ml = new MouseAdapter() {
        @Override/*from www.  ja  v  a2 s .  c  o  m*/
        public void mousePressed(MouseEvent e) {
            int selRow = currentTree.getRowForLocation(e.getX(), e.getY());
            TreePath selPath = currentTree.getPathForLocation(e.getX(), e.getY());
            if (selRow != -1 && ((DefaultMutableTreeNode) selPath.getLastPathComponent()).isLeaf()) {
                if (e.getClickCount() == 2) {
                    playSelectedTreeSound(selPath, Paths.get(vpkPath));
                }
            }
        }
    };
    currentTree.addMouseListener(ml);
}

From source file:edu.ucla.stat.SOCR.chart.ChartTree.java

/**
 * Receives notification of tree selection events and updates the demo 
 * display accordingly.//from   www .j  a  va  2  s.c  o  m
 * 
 * @param event  the event.
 */
public void valueChanged(TreeSelectionEvent event) {
    TreePath path = event.getPath();
    Object obj = path.getLastPathComponent();
    if (obj != null) {
        DefaultMutableTreeNode n = (DefaultMutableTreeNode) obj;
        Object userObj = n.getUserObject();
        if (userObj instanceof DemoDescription) {
            //                DemoDescription dd = (DemoDescription) userObj;
            //SwingUtilities.invokeLater(new DisplayDemo(this, dd));
        } else {
            /* this.chartContainer.removeAll();
                this.chartContainer.add(createNoDemoSelectedPanel());
                this.displayPanel.validate();
                displayDescription("select.html");*/
        }
    }
    System.out.println(obj);
}

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

/**
 * Add notebook node to folder node (on new notebook creation).
 *
 * @param notebookUri//from  w  ww.  ja v  a 2 s .co  m
 *            newly created notebook URI.
 */
public void addNotebookToFolder(String notebookUri) {
    logger.debug("  URI of created notebook is: " + notebookUri);
    if (notebookUri != null) {
        // add notebook to selected folder
        TreePath treePath = tree.getSelectionPath();
        String folderUri = (String) treeNodeToResourceUriMap.get(treePath.getLastPathComponent());
        logger.debug("Enclosing folder URI is: " + folderUri);
        if (folderUri != null) {
            try {
                // add notebook to folder
                MindRaider.labelCustodian.addOutline(folderUri, notebookUri);

                // now add it in the tree
                OutlineResource notebookResource = MindRaider.outlineCustodian.getActiveOutlineResource();
                addNotebookNode((DefaultMutableTreeNode) treePath.getLastPathComponent(),
                        notebookResource.resource.getMetadata().getUri().toASCIIString(),
                        notebookResource.getLabel());
            } catch (Exception e1) {
                logger.error("addNotebookToFolder(String)", e1);
                JOptionPane.showMessageDialog(TrashJPanel.this, "Outline Creation Error",
                        "Unable to add Outline to folder: " + e1.getMessage(), JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
    } else {
        logger.debug("Outline wont be added to folder - it's URI is null!");
    }
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopTree.java

@SuppressWarnings("unchecked")
@Override//from   w w w.j  a va2s.  co m
public Set<E> getSelected() {
    Set<E> selected = new HashSet<>();
    TreePath[] selectionPaths = impl.getSelectionPaths();
    if (selectionPaths != null) {
        for (TreePath selectionPath : selectionPaths) {
            Entity entity = model.getEntity(selectionPath.getLastPathComponent());
            if (entity != null) {
                selected.add((E) entity);
            }
        }
    }
    return selected;
}

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

protected DefaultMutableTreeNode getLastSelectedNode() {
    TreePath path = tree.getSelectionPath();
    if (path == null) {
        return null;
    }//from  w w  w  . j a v a2s.  c o m
    return (DefaultMutableTreeNode) path.getLastPathComponent();
}

From source file:gdt.jgui.entity.JEntityDigestDisplay.java

private void expandAll(JTree tree, TreePath path, boolean expand) {
    TreeNode node = (TreeNode) path.getLastPathComponent();
    if (node.getChildCount() >= 0) {
        Enumeration enumeration = node.children();
        while (enumeration.hasMoreElements()) {
            DefaultMutableTreeNode n = (DefaultMutableTreeNode) enumeration.nextElement();
            TreePath p = path.pathByAddingChild(n);
            expandAll(tree, p, expand);/*from  w w w .  jav a  2 s .  com*/
        }
    }
    if (expand) {
        tree.expandPath(path);
    } else {
        tree.collapsePath(path);
    }
}