Example usage for javax.swing JTree setShowsRootHandles

List of usage examples for javax.swing JTree setShowsRootHandles

Introduction

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

Prototype

@BeanProperty(description = "Whether the node handles are to be displayed.")
public void setShowsRootHandles(boolean newValue) 

Source Link

Document

Sets the value of the showsRootHandles property, which specifies whether the node handles should be displayed.

Usage

From source file:Main.java

public static void main(String[] args) {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Days");
    for (DaysOfTheWeek dotw : DaysOfTheWeek.values()) {
        root.add(new DefaultMutableTreeNode(dotw));
    }//w w  w .  j  av  a2  s.c o  m
    final DefaultTreeModel model = new DefaultTreeModel(root);
    JTree tree = new JTree(model);
    tree.setRootVisible(true);
    tree.setShowsRootHandles(true);
    ToolTipManager.sharedInstance().registerComponent(tree);
    tree.setCellRenderer(new MyTreeCellRenderer());
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new JScrollPane(tree));
    f.pack();
    f.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(10, 11, 212, 500);
    frame.getContentPane().add(scrollPane);

    JTree tree = new JTree(addNodes(new File(".")));
    tree.setRootVisible(false);//  ww  w  . j  a  v  a  2s . co m
    tree.setShowsRootHandles(true);

    tree.setBorder(new LineBorder(new Color(0, 0, 0)));
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    scrollPane.setViewportView(tree);

    tree.setCellRenderer(new FileTreeCellRenderer());

    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    MyTreeNode root = new MyTreeNode(1, 0);
    DefaultTreeModel model = new DefaultTreeModel(root);
    JProgressBar bar = new JProgressBar();
    PropertyChangeListener progressListener = new PropertyChangeListener() {
        @Override//from   w w w .  j  a  v a  2 s.  c  o m
        public void propertyChange(PropertyChangeEvent evt) {
            bar.setValue((Integer) evt.getNewValue());
        }
    };
    JTree tree = new JTree();
    tree.setShowsRootHandles(true);
    tree.addTreeWillExpandListener(new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            TreePath path = event.getPath();
            if (path.getLastPathComponent() instanceof MyTreeNode) {
                MyTreeNode node = (MyTreeNode) path.getLastPathComponent();
                node.loadChildren(model, progressListener);
            }
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {

        }
    });
    tree.setModel(model);
    root.loadChildren(model, progressListener);
    frame.add(new JScrollPane(tree));
    frame.add(bar, BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
}

From source file:TreeCellRendererImplementation.java

public TreeCellRendererImplementation() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("+");
    root.add(new DefaultMutableTreeNode(new Integer(3)));
    DefaultMutableTreeNode node = new DefaultMutableTreeNode("*");
    node.add(new DefaultMutableTreeNode("string"));
    node.add(new DefaultMutableTreeNode(new Short((short) 5)));
    root.add(node);/*ww w . j a v a  2  s.  co m*/

    TreeModel tm = new DefaultTreeModel(root);
    JTree tree = new JTree(tm);
    tree.setShowsRootHandles(true);
    tree.setCellRenderer(new MyRenderer());
    getContentPane().add(tree, BorderLayout.CENTER);
    setSize(400, 300);
    setVisible(true);
}

From source file:ca.sqlpower.architect.swingui.enterprise.SecurityPanel.java

public SecurityPanel(SPServerInfo serverInfo, Action closeAction, Dialog d, ArchitectSession session) {
    this.closeAction = closeAction;

    splitpane = new JSplitPane();
    panel = new JPanel();

    ArchitectClientSideSession clientSideSession = ArchitectClientSideSession.getSecuritySessions()
            .get(serverInfo.getServerAddress());

    //Displaying an indeterminate progress bar in place of the split pane
    //until the security session has loaded fully.
    if (clientSideSession.getUpdater().getRevision() <= 0) {
        JLabel messageLabel = new JLabel("Opening");
        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);

        DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("pref:grow, 5dlu, pref"));
        builder.setDefaultDialogBorder();
        builder.append(messageLabel, 3);
        builder.nextLine();//www  .ja va 2s  .  com
        builder.append(progressBar, 3);

        UpdateListener l = new UpdateListener() {

            @Override
            public void workspaceDeleted() {
                //do nothing
            }

            @Override
            public boolean updatePerformed(AbstractNetworkConflictResolver resolver) {
                panel.removeAll();
                panel.add(splitpane);
                dialog.pack();
                refreshTree();
                return true;
            }

            @Override
            public boolean updateException(AbstractNetworkConflictResolver resolver, Throwable t) {
                //do nothing, the error will be handled elsewhere
                return true;
            }

            @Override
            public void preUpdatePerformed(AbstractNetworkConflictResolver resolver) {
                //do nothing
            }
        };

        clientSideSession.getUpdater().addListener(l);
        panel.add(builder.getPanel());
    }
    this.securityWorkspace = clientSideSession.getWorkspace();
    this.username = serverInfo.getUsername();
    this.dialog = d;
    this.session = session;

    try {
        digester = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    rootNode.add(usersNode);
    rootNode.add(groupsNode);

    rightSidePanel = new JPanel();

    tree = new JTree(rootNode);
    tree.addTreeSelectionListener(treeListener);
    tree.setRootVisible(false);
    tree.setShowsRootHandles(true);
    tree.setCellRenderer(new DefaultTreeCellRenderer() {
        public 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);
            Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
            if (userObject instanceof User) {
                setIcon(USER_ICON);
            } else if (userObject instanceof Group) {
                setIcon(GROUP_ICON);
            }
            return this;
        }
    });

    treePane = new JScrollPane(tree);
    treePane.setPreferredSize(new Dimension(200, treePane.getPreferredSize().height));

    tree.addMouseListener(popupListener);

    splitpane.setRightComponent(rightSidePanel);
    splitpane.setLeftComponent(treePane);

    if (clientSideSession.getUpdater().getRevision() > 0) {
        panel.removeAll();
        panel.add(splitpane);
    }

    refreshTree();

    try {
        tree.setSelectionPath(new TreePath(usersNode.getFirstChild()));
    } catch (NoSuchElementException e) {
    } // This just means that the node has no children, so we cannot expand the path.
}

From source file:it.unibas.spicygui.controllo.window.operator.ProjectTreeGenerator.java

public void generateTree(JTree jTree) {
    Scenarios scenarios = (Scenarios) modello.getBean(Costanti.SCENARIOS);
    DefaultMutableTreeNode nodeRoot = new DefaultMutableTreeNode(
            new TreeTopComponentAdapter(null, false, true, false));
    for (IScenario scenario : scenarios.getListaSceneri()) {
        analizzaScenario(nodeRoot, (Scenario) scenario);
    }//ww w  .  ja  v  a  2  s  .c  om
    ((DefaultTreeModel) jTree.getModel()).setRoot(nodeRoot);
    jTree.setRootVisible(false);
    jTree.setShowsRootHandles(true);
    TreeRenderer rendererTree = new TreeRenderer();
    jTree.setCellRenderer(rendererTree);
    return;
}

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  . j a  v  a  2  s .  co m*/
    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:org.apache.jmeter.gui.MainFrame.java

/**
 * Create and initialize the GUI representation of the test tree.
 *
 * @param treeModel/*w w  w .  java  2s.co  m*/
 *            the test tree model
 * @param treeListener
 *            the test tree listener
 *
 * @return the initialized test tree GUI
 */
private JTree makeTree(TreeModel treeModel, JMeterTreeListener treeListener) {
    JTree treevar = new JTree(treeModel) {
        private static final long serialVersionUID = 240L;

        @Override
        public String getToolTipText(MouseEvent event) {
            TreePath path = this.getPathForLocation(event.getX(), event.getY());
            if (path != null) {
                Object treeNode = path.getLastPathComponent();
                if (treeNode instanceof DefaultMutableTreeNode) {
                    Object testElement = ((DefaultMutableTreeNode) treeNode).getUserObject();
                    if (testElement instanceof TestElement) {
                        String comment = ((TestElement) testElement).getComment();
                        if (comment != null && comment.length() > 0) {
                            return comment;
                        }
                    }
                }
            }
            return null;
        }
    };
    treevar.setToolTipText("");
    treevar.setCellRenderer(getCellRenderer());
    treevar.setRootVisible(false);
    treevar.setShowsRootHandles(true);

    treeListener.setJTree(treevar);
    treevar.addTreeSelectionListener(treeListener);
    treevar.addMouseListener(treeListener);
    treevar.addKeyListener(treeListener);

    // enable drag&drop, install a custom transfer handler
    treevar.setDragEnabled(true);
    treevar.setDropMode(DropMode.ON_OR_INSERT);
    treevar.setTransferHandler(new JMeterTreeTransferHandler());

    addQuickComponentHotkeys(treevar);

    return treevar;
}

From source file:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultTreeView.java

@Override
public void refreshView(final ViewState state) {
    Rectangle visibleRect = null;
    if (this.tree != null) {
        visibleRect = this.tree.getVisibleRect();
    }//from ww w  .  j  a  v a  2  s.  c o  m

    this.removeAll();

    this.actionsMenu = this.createPopupMenu(state);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("WORKFLOWS");
    for (ModelGraph graph : state.getGraphs()) {
        root.add(this.buildTree(graph, state));
    }
    tree = new JTree(root);
    tree.setShowsRootHandles(true);
    tree.setRootVisible(false);
    tree.add(this.actionsMenu);

    if (state.getSelected() != null) {
        // System.out.println("SELECTED: " + state.getSelected());
        TreePath treePath = this.getTreePath(root, state.getSelected());
        if (state.getCurrentMetGroup() != null) {
            treePath = this.getTreePath(treePath, state);
        } else if (Boolean.parseBoolean(state.getFirstPropertyValue(EXPAND_STATIC_METADATA))) {
            DefaultMutableTreeNode baseNode = (DefaultMutableTreeNode) treePath.getLastPathComponent();
            for (int i = 0; i < baseNode.getChildCount(); i++) {
                if (((DefaultMutableTreeNode) baseNode.getChildAt(i)).getUserObject()
                        .equals("static-metadata")) {
                    treePath = new TreePath(((DefaultMutableTreeNode) baseNode.getChildAt(i)).getPath());
                    break;
                }
            }
        } else if (Boolean.parseBoolean(state.getFirstPropertyValue(EXPAND_PRECONDITIONS))) {
            if (treePath == null) {
                treePath = this.getTreePath(root, state.getSelected().getPreConditions());
            }
            DefaultMutableTreeNode baseNode = (DefaultMutableTreeNode) treePath.getLastPathComponent();
            for (int i = 0; i < baseNode.getChildCount(); i++) {
                if (((DefaultMutableTreeNode) baseNode.getChildAt(i)).getUserObject()
                        .equals("pre-conditions")) {
                    treePath = new TreePath(((DefaultMutableTreeNode) baseNode.getChildAt(i)).getPath());
                    break;
                }
            }
        } else if (Boolean.parseBoolean(state.getFirstPropertyValue(EXPAND_POSTCONDITIONS))) {
            if (treePath == null) {
                treePath = this.getTreePath(root, state.getSelected().getPostConditions());
            }
            DefaultMutableTreeNode baseNode = (DefaultMutableTreeNode) treePath.getLastPathComponent();
            for (int i = 0; i < baseNode.getChildCount(); i++) {
                if (((DefaultMutableTreeNode) baseNode.getChildAt(i)).getUserObject()
                        .equals("post-conditions")) {
                    treePath = new TreePath(((DefaultMutableTreeNode) baseNode.getChildAt(i)).getPath());
                    break;
                }
            }
        }
        this.tree.expandPath(treePath);
        this.tree.setSelectionPath(treePath);
    }

    tree.addTreeSelectionListener(new TreeSelectionListener() {

        public void valueChanged(TreeSelectionEvent e) {
            if (e.getPath().getLastPathComponent() instanceof DefaultMutableTreeNode) {
                DefaultTreeView.this.resetProperties(state);
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
                if (node.getUserObject() instanceof ModelGraph) {
                    state.setSelected((ModelGraph) node.getUserObject());
                    state.setCurrentMetGroup(null);
                    DefaultTreeView.this.notifyListeners();
                } else if (node.getUserObject().equals("static-metadata")
                        || node.getUserObject().equals("pre-conditions")
                        || node.getUserObject().equals("post-conditions")) {
                    state.setSelected((ModelGraph) ((DefaultMutableTreeNode) node.getParent()).getUserObject());
                    state.setCurrentMetGroup(null);
                    state.setProperty(EXPAND_STATIC_METADATA,
                            Boolean.toString(node.getUserObject().equals("static-metadata")));
                    state.setProperty(EXPAND_PRECONDITIONS,
                            Boolean.toString(node.getUserObject().equals("pre-conditions")));
                    state.setProperty(EXPAND_POSTCONDITIONS,
                            Boolean.toString(node.getUserObject().equals("post-conditions")));
                    DefaultTreeView.this.notifyListeners();
                } else if (node.getUserObject() instanceof ConcurrentHashMap) {
                    DefaultMutableTreeNode metNode = null;
                    String group = null;
                    Object[] path = e.getPath().getPath();
                    for (int i = path.length - 1; i >= 0; i--) {
                        if (((DefaultMutableTreeNode) path[i]).getUserObject() instanceof ModelGraph) {
                            metNode = (DefaultMutableTreeNode) path[i];
                            break;
                        } else if (((DefaultMutableTreeNode) path[i])
                                .getUserObject() instanceof ConcurrentHashMap) {
                            if (group == null) {
                                group = (String) ((ConcurrentHashMap<String, String>) ((DefaultMutableTreeNode) path[i])
                                        .getUserObject()).keySet().iterator().next();
                            } else {
                                group = (String) ((ConcurrentHashMap<String, String>) ((DefaultMutableTreeNode) path[i])
                                        .getUserObject()).keySet().iterator().next() + "/" + group;
                            }
                        }
                    }
                    ModelGraph graph = (ModelGraph) metNode.getUserObject();
                    state.setSelected(graph);
                    state.setCurrentMetGroup(group);
                    DefaultTreeView.this.notifyListeners();
                } else {
                    state.setSelected(null);
                    DefaultTreeView.this.notifyListeners();
                }
            }
        }

    });
    tree.setCellRenderer(new TreeCellRenderer() {

        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
            if (node.getUserObject() instanceof String) {
                JPanel panel = new JPanel();
                panel.setLayout(new BorderLayout());
                JLabel label = new JLabel((String) node.getUserObject());
                label.setForeground(Color.blue);
                panel.add(label, BorderLayout.CENTER);
                panel.setBackground(selected ? Color.lightGray : Color.white);
                return panel;
            } else if (node.getUserObject() instanceof ModelGraph) {
                JPanel panel = new JPanel();
                panel.setLayout(new BorderLayout());
                JLabel iconLabel = new JLabel(
                        ((ModelGraph) node.getUserObject()).getModel().getExecutionType() + ": ");
                iconLabel.setForeground(((ModelGraph) node.getUserObject()).getModel().getColor());
                iconLabel.setBackground(Color.white);
                JLabel idLabel = new JLabel(((ModelGraph) node.getUserObject()).getModel().getModelName());
                idLabel.setBackground(Color.white);
                panel.add(iconLabel, BorderLayout.WEST);
                panel.add(idLabel, BorderLayout.CENTER);
                panel.setBackground(selected ? Color.lightGray : Color.white);
                return panel;
            } else if (node.getUserObject() instanceof ConcurrentHashMap) {
                JPanel panel = new JPanel();
                panel.setLayout(new BorderLayout());
                String group = (String) ((ConcurrentHashMap<String, String>) node.getUserObject()).keySet()
                        .iterator().next();
                JLabel nameLabel = new JLabel(group + " : ");
                nameLabel.setForeground(Color.blue);
                nameLabel.setBackground(Color.white);
                JLabel valueLabel = new JLabel(
                        ((ConcurrentHashMap<String, String>) node.getUserObject()).get(group));
                valueLabel.setForeground(Color.darkGray);
                valueLabel.setBackground(Color.white);
                panel.add(nameLabel, BorderLayout.WEST);
                panel.add(valueLabel, BorderLayout.EAST);
                panel.setBackground(selected ? Color.lightGray : Color.white);
                return panel;
            } else {
                return new JLabel();
            }
        }

    });
    tree.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3 && DefaultTreeView.this.tree.getSelectionPath() != null) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) DefaultTreeView.this.tree
                        .getSelectionPath().getLastPathComponent();
                if (node.getUserObject() instanceof String && !(node.getUserObject().equals("pre-conditions")
                        || node.getUserObject().equals("post-conditions"))) {
                    return;
                }
                orderSubMenu.setEnabled(node.getUserObject() instanceof ModelGraph
                        && !((ModelGraph) node.getUserObject()).isCondition()
                        && ((ModelGraph) node.getUserObject()).getParent() != null);
                DefaultTreeView.this.actionsMenu.show(DefaultTreeView.this.tree, e.getX(), e.getY());
            }
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    });
    this.scrollPane = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    this.add(this.scrollPane, BorderLayout.CENTER);
    if (visibleRect != null) {
        this.tree.scrollRectToVisible(visibleRect);
    }

    this.revalidate();
}

From source file:org.apache.oodt.cas.workflow.gui.perspective.view.impl.GlobalConfigView.java

@Override
public void refreshView(ViewState state) {

    Rectangle visibleRect = null;
    if (this.tree != null) {
        visibleRect = this.tree.getVisibleRect();
    }//from   w w w.j a v a 2 s .  c  o m

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("GlobalConfig");

    if (state != null && state.getGlobalConfigGroups() != null) {
        if (globalConfig != null && globalConfig.keySet().equals(state.getGlobalConfigGroups().keySet())
                && globalConfig.values().equals(state.getGlobalConfigGroups().values())) {
            return;
        }

        this.removeAll();

        for (ConfigGroup group : (globalConfig = state.getGlobalConfigGroups()).values()) {
            HashSet<String> keys = new HashSet<String>();
            DefaultMutableTreeNode groupNode = new DefaultMutableTreeNode(new Group(group.getName()));
            root.add(groupNode);
            for (String key : group.getMetadata().getAllKeys()) {
                keys.add(key);
                DefaultMutableTreeNode keyNode = new DefaultMutableTreeNode(new Key(key));
                groupNode.add(keyNode);
                DefaultMutableTreeNode valueNode = new DefaultMutableTreeNode(
                        new Value(StringUtils.join(group.getMetadata().getAllMetadata(key), ",")));
                keyNode.add(valueNode);
            }
            if (group.getExtends() != null) {
                List<String> extendsGroups = new Vector<String>(group.getExtends());
                Collections.reverse(extendsGroups);
                for (String extendsGroup : extendsGroups) {
                    List<String> groupKeys = state.getGlobalConfigGroups().get(extendsGroup).getMetadata()
                            .getAllKeys();
                    groupKeys.removeAll(keys);
                    if (groupKeys.size() > 0) {
                        for (String key : groupKeys) {
                            if (!keys.contains(key)) {
                                keys.add(key);
                                DefaultMutableTreeNode keyNode = new DefaultMutableTreeNode(
                                        new ExtendsKey(extendsGroup, key));
                                groupNode.add(keyNode);
                                DefaultMutableTreeNode valueNode = new DefaultMutableTreeNode(
                                        new ExtendsValue(StringUtils.join(state.getGlobalConfigGroups()
                                                .get(extendsGroup).getMetadata().getAllMetadata(key), ",")));
                                keyNode.add(valueNode);
                            }
                        }
                    }
                }
            }
        }

        tree = new JTree(root);
        tree.setShowsRootHandles(true);
        tree.setRootVisible(false);

        tree.setCellRenderer(new TreeCellRenderer() {

            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                    boolean expanded, boolean leaf, int row, boolean hasFocus) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                if (node.getUserObject() instanceof Key) {
                    JPanel panel = new JPanel();
                    panel.setLayout(new BorderLayout());
                    JLabel label = new JLabel(node.getUserObject().toString());
                    label.setForeground(Color.darkGray);
                    panel.add(label, BorderLayout.CENTER);
                    panel.setBackground(selected ? Color.lightGray : Color.white);
                    return panel;
                } else if (node.getUserObject() instanceof ExtendsKey) {
                    JPanel panel = new JPanel();
                    panel.setLayout(new BorderLayout());
                    ExtendsKey key = (ExtendsKey) node.getUserObject();
                    JLabel groupLabel = new JLabel("(" + key.getGroup() + ") ");
                    groupLabel.setForeground(Color.black);
                    JLabel keyLabel = new JLabel(key.getValue());
                    keyLabel.setForeground(Color.gray);
                    panel.add(groupLabel, BorderLayout.WEST);
                    panel.add(keyLabel, BorderLayout.CENTER);
                    panel.setBackground(selected ? Color.lightGray : Color.white);
                    return panel;
                } else if (node.getUserObject() instanceof Group) {
                    JPanel panel = new JPanel();
                    panel.setLayout(new BorderLayout());
                    JLabel label = new JLabel(node.getUserObject().toString());
                    label.setForeground(Color.black);
                    label.setBackground(Color.white);
                    panel.add(label, BorderLayout.CENTER);
                    panel.setBackground(selected ? Color.lightGray : Color.white);
                    return panel;
                } else if (node.getUserObject() instanceof Value) {
                    JPanel panel = new JPanel();
                    panel.setLayout(new BorderLayout());
                    panel.setBorder(new EtchedBorder(1));
                    JLabel label = new JLabel(node.getUserObject().toString());
                    label.setForeground(Color.black);
                    panel.add(label, BorderLayout.CENTER);
                    panel.setBackground(selected ? Color.lightGray : Color.white);
                    return panel;
                } else if (node.getUserObject() instanceof ExtendsValue) {
                    JPanel panel = new JPanel();
                    panel.setLayout(new BorderLayout());
                    panel.setBorder(new EtchedBorder(1));
                    JLabel label = new JLabel(node.getUserObject().toString());
                    label.setForeground(Color.gray);
                    panel.add(label, BorderLayout.CENTER);
                    panel.setBackground(selected ? Color.lightGray : Color.white);
                    return panel;
                } else {
                    return new JLabel();
                }
            }

        });
    }

    this.setBorder(new EtchedBorder());
    JLabel panelName = new JLabel("Global-Config Groups");
    panelName.setBorder(new EtchedBorder());
    this.add(panelName, BorderLayout.NORTH);
    JScrollPane scrollPane = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    tabbedPane = new JTabbedPane();
    tabbedPane.addTab("Tree", scrollPane);
    tabbedPane.addTab("Table", new JPanel());

    this.add(tabbedPane, BorderLayout.CENTER);

    if (visibleRect != null) {
        this.tree.scrollRectToVisible(visibleRect);
    }

    this.revalidate();
}