Example usage for javax.swing JTree setCellRenderer

List of usage examples for javax.swing JTree setCellRenderer

Introduction

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

Prototype

@BeanProperty(description = "The TreeCellRenderer that will be used to draw each cell.")
public void setCellRenderer(TreeCellRenderer x) 

Source Link

Document

Sets the TreeCellRenderer that will be used to draw each cell.

Usage

From source file:Main.java

public Main(File dir) {
    setLayout(new BorderLayout());
    JTree tree = new JTree(addNodes(null, projectFile));
    tree.setCellRenderer(new MyTreeCellRenderer());
    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
            System.out.println("You selected " + node);
        }/*ww w.  ja v a 2  s  .c  o m*/
    });

    JScrollPane scrollpane = new JScrollPane();
    scrollpane.getViewport().add(tree);
    add(scrollpane, BorderLayout.CENTER);
}

From source file:it.unibas.spicygui.controllo.datasource.operators.GenerateInstanceTree.java

public JTree buildInstanceTree(INode instanceRoot, IDataSourceProxy dataSource) {
    InstanceTreeVisitor visitor = new InstanceTreeVisitor(dataSource);
    instanceRoot.accept(visitor);//w w  w  . j  av  a2s .  c o m
    JTree instanceTree = new JTree(visitor.getResult());
    TreeRenderer rendererTree = new TreeRenderer();
    instanceTree.setCellRenderer(rendererTree);
    return instanceTree;
}

From source file:com.github.rholder.gradle.ui.DependencyViewerStandalone.java

public void updateView(GradleNode rootDependency, GradleNode selectedDependency) {
    // TODO replace this hack with something that populates the GradleNode graph

    DefaultMutableTreeNode fullRoot = new DefaultMutableTreeNode(new GradleNode("Project Dependencies"));
    if (rootDependency == null) {
        DefaultMutableTreeNode loading = new DefaultMutableTreeNode(new GradleNode("Loading..."));
        fullRoot.add(loading);// w w  w.  j a  v  a 2  s. c o m
    } else {
        DefaultMutableTreeNode flattenedRoot = convertToSortedTreeNode(rootDependency);
        DefaultMutableTreeNode hierarchyRoot = convertToHierarchyTreeNode(rootDependency);
        fullRoot.add(flattenedRoot);
        fullRoot.add(hierarchyRoot);
    }

    TreeModel treeModel = new DefaultTreeModel(fullRoot);
    final JTree fullTree = new JTree(treeModel);
    fullTree.setCellRenderer(dependencyCellRenderer);

    // expand path for first level from root
    //fullTree.expandPath(new TreePath(hierarchyRoot.getNextNode().getPath()));

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            if (gradleBaseDir != null) {
                setTitle(TITLE + " - " + gradleBaseDir);
            }
            splitter.setLeftComponent(new JScrollPane(fullTree));
            splitter.setRightComponent(new JScrollPane(information));
            splitter.setDividerLocation(0.75);
        }
    });
}

From source file:it.unibas.spicygui.controllo.datasource.operators.GenerateSchemaTree.java

public JTree buildSchemaTree(IDataSourceProxy dataSource) {
    SchemaTreeVisitor visitor = new SchemaTreeVisitor(dataSource);
    //        if (!dataSource.getType().equalsIgnoreCase(SpicyEngineConstants.TYPE_RELATIONAL)) {
    dataSource.getIntermediateSchema().accept(visitor);
    //        }else {
    //            dataSource.getOriginalSchema().accept(visitor);
    //        }/*from   ww w. j  a va 2 s. c om*/
    JTree schemaTree = new JTree(visitor.getResult());
    TreeRenderer rendererTree = new TreeRenderer();
    schemaTree.setCellRenderer(rendererTree);
    return schemaTree;
}

From source file:ec.nbdemetra.ui.demo.ComponentsDemo.java

public ComponentsDemo() {
    initStaticResources();/*www. j a va2s  . c om*/

    final Map<Id, Component> demoData = lookupComponents();

    final JPanel main = new JPanel(new BorderLayout());
    final JTree tree = new JTree();
    tree.setRootVisible(false);
    tree.setCellRenderer(new IdRenderer(demoData));

    IdsTree.fill(tree, Lists.newArrayList(demoData.keySet()));
    expandAll(tree);

    tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
        @Override
        public void valueChanged(TreeSelectionEvent e) {
            TreePath p = tree.getSelectionPath();
            if (p != null) {
                main.removeAll();
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent();
                Id id = IdsTree.translate(node);
                Component c = demoData.get(id);
                main.add(c != null ? c : new JPanel());
                main.validate();
                main.repaint();
            }
        }
    });

    JTsList dragDrop = new JTsList();
    dragDrop.setShowHeader(false);
    dragDrop.setInformation(new ITsList.InfoType[] { ITsList.InfoType.TsIdentifier, ITsList.InfoType.Data });
    dragDrop.setPreferredSize(new Dimension(200, 200));
    dragDrop.setTsAction(DemoTsActions.DO_NOTHING);

    JSplitPane left = NbComponents.newJSplitPane(JSplitPane.VERTICAL_SPLIT, NbComponents.newJScrollPane(tree),
            dragDrop);
    JSplitPane splitPane = NbComponents.newJSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, main);
    splitPane.getLeftComponent().setPreferredSize(new Dimension(200, 400));

    setLayout(new BorderLayout());
    add(splitPane, BorderLayout.CENTER);
}

From source file:edu.ku.brc.specify.config.DebugLoggerDialog.java

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

    configureLoggers();/*from  www .  ja  v  a2  s .  c  om*/

    root = new LoggerNode(null, "Root");
    for (String loggerName : sortedNames) {
        buildTree(loggers.get(loggerName), root, StringUtils.split(loggerName, '.'), 0);
    }

    JTree tree = new JTree(root);
    tree.setCellRenderer(new CheckRenderer());
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.putClientProperty("JTree.lineStyle", "Angled");
    tree.addMouseListener(new NodeSelectionListener(tree));

    contentPanel = new JScrollPane(tree);

    mainPanel.add(contentPanel, BorderLayout.CENTER);

    setSize(500, 500);
}

From source file:DOMTreeTest.java

/**
     * Open a file and load the document.
     */// w  ww  . ja v a  2s  .  co  m
    public void openFile() {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));

        chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
            }

            public String getDescription() {
                return "XML files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if (r != JFileChooser.APPROVE_OPTION)
            return;
        final File file = chooser.getSelectedFile();

        new SwingWorker<Document, Void>() {
            protected Document doInBackground() throws Exception {
                if (builder == null) {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    builder = factory.newDocumentBuilder();
                }
                return builder.parse(file);
            }

            protected void done() {
                try {
                    Document doc = get();
                    JTree tree = new JTree(new DOMTreeModel(doc));
                    tree.setCellRenderer(new DOMTreeCellRenderer());

                    setContentPane(new JScrollPane(tree));
                    validate();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(DOMTreeFrame.this, e);
                }
            }
        }.execute();
    }

From source file:MyData.java

public Main() {
    super();// ww w  . jav  a 2 s . c o  m
    JTree tree = new JTree(getRootNode()) {
        public boolean isPathEditable(TreePath path) {
            Object comp = path.getLastPathComponent();
            if (comp instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) comp;
                Object userObject = node.getUserObject();
                if (userObject instanceof Main) {
                    return true;
                }
            }
            return false;
        }
    };
    QuestionCellRenderer renderer = new QuestionCellRenderer();
    tree.setCellRenderer(renderer);
    QuestionCellEditor editor = new QuestionCellEditor();
    tree.setCellEditor(editor);
    tree.setEditable(true);
    JScrollPane jsp = new JScrollPane(tree);
    getContentPane().add(jsp);
}

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 ww  w.  jav  a  2  s  . com
    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:net.sf.taverna.t2.workbench.views.results.processor.RenderedProcessorResultComponent.java

/**
 * Update the component based on the node selected from the
 * ResultViewComponent tree.//from   www. j av  a 2 s .c om
 */
public void updateResult() {
    if (recognisedRenderersForMimeType == null)
        recognisedRenderersForMimeType = new ArrayList<>();
    if (otherRenderers == null)
        otherRenderers = new ArrayList<>();

    ProcessorResultTreeNode result = (ProcessorResultTreeNode) node;

    // Reference to the result data
    path = result.getReference();

    // Enable the combo box
    renderersComboBox.setEnabled(true);

    /*
     * Update the 'save result' buttons appropriately as the result node had
     * changed
     */
    for (int i = 0; i < saveButtonsPanel.getComponents().length; i++) {
        JButton saveButton = (JButton) saveButtonsPanel.getComponent(i);
        SaveIndividualResultSPI action = (SaveIndividualResultSPI) (saveButton.getAction());
        // Update the action with the new result reference
        action.setResultReference(path);
        saveButton.setEnabled(true);
    }

    if (DataBundles.isValue(path) || DataBundles.isReference(path)) {
        // Enable refresh button
        refreshButton.setEnabled(true);

        List<MimeType> mimeTypes = new ArrayList<>();
        try (InputStream inputstream = RendererUtils.getInputStream(path)) {
            mimeTypes.addAll(getMimeTypes(inputstream));
        } catch (IOException e) {
            logger.warn("Error getting mimetype", e);
        }

        if (mimeTypes.isEmpty()) {
            // If MIME types is empty - add "plain/text" MIME type
            mimeTypes.add(new MimeType("text/plain"));
        } else if (mimeTypes.size() == 1 && mimeTypes.get(0).toString().equals("chemical/x-fasta")) {
            /*
             * If MIME type is recognised as "chemical/x-fasta" only then
             * this might be an error from MIME magic (i.e., sometimes it
             * recognises stuff that is not "chemical/x-fasta" as
             * "chemical/x-fasta" and then Seq Vista renderer is used that
             * causes errors) - make sure we also add the renderers for
             * "text/plain" and "text/xml" as it is most probably just
             * normal xml text and push the "chemical/x-fasta" to the bottom
             * of the list.
             */
            mimeTypes.add(0, new MimeType("text/plain"));
            mimeTypes.add(1, new MimeType("text/xml"));
        }

        for (MimeType mimeType : mimeTypes)
            for (Renderer renderer : rendererRegistry.getRenderersForMimeType(mimeType.toString()))
                if (!recognisedRenderersForMimeType.contains(renderer))
                    recognisedRenderersForMimeType.add(renderer);
        // if there are no renderers then force text/plain
        if (recognisedRenderersForMimeType.isEmpty())
            recognisedRenderersForMimeType = rendererRegistry.getRenderersForMimeType("text/plain");

        /*
         * Add all other available renderers that are not recognised to be
         * able to handle the MIME type of the result
         */
        otherRenderers = rendererRegistry.getRenderers();
        otherRenderers.removeAll(recognisedRenderersForMimeType);

        mimeList = new String[recognisedRenderersForMimeType.size() + otherRenderers.size()];
        rendererList = new ArrayList<>();

        /*
         * First add the ones that can handle the MIME type of the result
         * item
         */
        for (int i = 0; i < recognisedRenderersForMimeType.size(); i++) {
            mimeList[i] = recognisedRenderersForMimeType.get(i).getType();
            rendererList.add(recognisedRenderersForMimeType.get(i));
        }
        // Then add the other renderers just in case
        for (int i = 0; i < otherRenderers.size(); i++) {
            mimeList[recognisedRenderersForMimeType.size() + i] = otherRenderers.get(i).getType();
            rendererList.add(otherRenderers.get(i));
        }

        renderersComboBox.setModel(new DefaultComboBoxModel<>(mimeList));

        if (mimeList.length > 0) {
            int index = 0;

            // Find the index of the current MIME type for this output port.
            for (int i = 0; i < mimeList.length; i++)
                if (mimeList[i].equals(lastUsedMIMEtype)) {
                    index = i;
                    break;
                }

            int previousindex = renderersComboBox.getSelectedIndex();
            renderersComboBox.setSelectedIndex(index);
            /*
             * force rendering as setSelectedIndex will not fire an
             * itemstatechanged event if previousindex == index and we still
             * need render the result as we may have switched from a
             * different result item in a result list but the renderer index
             * stayed the same
             */
            if (previousindex == index)
                renderResult(); // draw the rendered result component
        }
    } else if (DataBundles.isError(path)) {
        // Disable refresh button
        refreshButton.setEnabled(false);

        @SuppressWarnings("unused")
        ErrorDocument errorDocument;
        try {
            errorDocument = DataBundles.getError(path);
        } catch (IOException e) {
            logger.warn("Error getting the error document", e);
        }

        // Reset the renderers as we have an error item
        recognisedRenderersForMimeType = null;
        otherRenderers = null;

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Error Trace");

        // TODO handle error documents
        // ResultsUtils.buildErrorDocumentTree(root, errorDocument, referenceService);

        JTree errorTree = new JTree(root);

        errorTree.setCellRenderer(new DefaultTreeCellRenderer() {
            @Override
            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                    boolean expanded, boolean leaf, int row, boolean hasFocus) {
                Component renderer = null;
                if (value instanceof DefaultMutableTreeNode) {
                    Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
                    if (userObject instanceof ErrorDocument)
                        renderer = getErrorDocumentRenderer(tree, selected, expanded, leaf, row, hasFocus,
                                (ErrorDocument) userObject);
                }
                if (renderer == null)
                    renderer = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row,
                            hasFocus);
                if (renderer instanceof JLabel) {
                    JLabel label = (JLabel) renderer;
                    label.setIcon(null);
                }
                return renderer;
            }

            private Component getErrorDocumentRenderer(JTree tree, boolean selected, boolean expanded,
                    boolean leaf, int row, boolean hasFocus, ErrorDocument errorDocument) {
                return super.getTreeCellRendererComponent(tree,
                        "<html>" + escapeHtml(errorDocument.getMessage()) + "</html>", selected, expanded, leaf,
                        row, hasFocus);
            }
        });

        renderersComboBox.setModel(new DefaultComboBoxModel<>(new String[] { ERROR_DOCUMENT }));
        renderedResultPanel.removeAll();
        renderedResultPanel.add(errorTree, CENTER);
        repaint();
    }
}