Different Color Nodes in JTree?

Is there a simple way to get nodes in a JTree to appear in different colors? I've only been able to change to color of all the text of a tree. I'd like to avoid writing my own renderers and such... any suggestions? Thanks everyone.

Check the following site, it may help:
http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
It's definitely a worth to visit page.

Similar Messages

  • Set different color for one JTree node

    hello,
    I managed to find how to set a color for Jtree nodes but the problem is that with my method all the nodes will b the same color whereas i'm looking to have nodes of different color depending on the situation.
    the method for setting all Jtree nodes the same color(other than black):
    tree.setCellRenderer(
    new DefaultTreeCellRenderer() {
       public Color getTextNonSelectionColor() {
         return Color.lightGray; } });I WANT TO CHOSSE EACH COLOR FOR EACH NODE
    help plz
    thanks

    You need to implement TreeCellRenderer interface
    public Component getTreeCellRendererComponent(JTree tree,
                                                  Object value,
                                                  boolean sel,
                                                  boolean expanded,
                                                  boolean leaf,
                                                  int row,
                                                  boolean hasFocus)You can know which node is rendering by check value argument. Please read DefaultTreeCellRenderer's code.

  • Ho to set different color to different Jtree Nodes

    hi,
    In a JTree I need to remark with a different color the leaves that bring
    different categories of information.
    I wrote this function to achieve this purpose:
    private void assignRenderToTrees(JTree jTree, String category) {
             // a different color depending from the category
            Color color = null;
            String ssttrr = category.substring(0, 1);
            if (ssttrr.compareTo("*") == 0) {
                color = Color.YELLOW;
             if (ssttrr.compareTo("^") == 0) {
                color = Color.BLUE;
            // the same icon to all nodes
            String pathXopen = "resources_toShowMouth/oneToothGoodMod.gif";
            URL imgURLXopen = MedidentStart.class.getResource(pathXclose);
            ImageIcon iconXopen = new ImageIcon(imgURLXopen);
            if (iconXopen != null) {
                DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
                renderer.setLeafIcon(null);
                renderer.setClosedIcon(iconXclose);
                renderer.setOpenIcon(iconXopen);
                renderer.setBackgroundNonSelectionColor(color);
                jTree.setCellRenderer(renderer);
            } else {
                System.err.println("Leaf icon missing; using default.");
        } // assignIconsToTree()But in this way, I don't get the selection for the leaf, depending for the category.
    Instead I get all the nodes with the same color.
    I can believe that this happen because I am getting the nodes of all the tree,
    instead the single nodes..., but I am not able to select a single node to
    assign the color...
    I would have an help to do it..
    thank you
    regards
    tonyMrsangelo.

    hi,
    thank you for your kind answer.
    You are right..., JTree are a large framework that I don't know very good.
    ..So often I try to arrange a solution witouth to know good the environment where I am working ...
    This is the reason I changed the approch to the problem in the different time when I posted my ask.
    At any rate now I reproduced the problem selecting a part of my program.
    To use tree.setCellRenderer(renderer) is I found in an example that I was not
    able to reproduce.
    I hope to know what is wrong in the code I posted...
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    public class SSCCE_ForPeriodontalCharting extends JFrame {
        PanelArcSupSx panelArcSupSx;//
        public SSCCE_ForPeriodontalCharting() {
            panelArcSupSx = new PanelArcSupSx();
            add(panelArcSupSx);
            setSize(900, 300);
            setVisible(true);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String[] args) {
            SSCCE_ForPeriodontalCharting xxx = new SSCCE_ForPeriodontalCharting();
    } // class SSCCE_ForPeriodontalCharting
    class PanelArcSupSx extends JPanel {
        JScrollPane jScrollPane[];
        JTree jTreeForArcSS[];
        DefaultMutableTreeNode[] rootNodeArcSS;
        Dimension dimPrefSemiArcPanels = new Dimension(850, 140);
        Dimension treePrefDim = new Dimension(100, 110);
        Dimension dimMinSemiArcPanels = new Dimension(650, 90);
        String[] treesContents = {        "* aaaaa - 2",     "* bbbbb - 2",
            "^ ccccc - 2",    "ddddd - 3",     "* eeeee - 2",
            "fffff - 6",    "* ggggg - 6",     "* hhhhh - 5",
            "* iiiii - 5",   "* kkkkkkk - 1",   "^ llllll - 5",
            "^ mmmmmmm - 2",   "nnnnnnn - 4",    "^ oooooo - 4",
            "* pppppppp - 4"};
        public PanelArcSupSx() { // costruttore
            this.setMinimumSize(dimMinSemiArcPanels);
            this.setPreferredSize(dimPrefSemiArcPanels);
            setLayout(new FlowLayout());
            jScrollPane = new JScrollPane[8];
            jTreeForArcSS = new JTree[8];
            rootNodeArcSS = new DefaultMutableTreeNode[8];
            // arc sup Sx
            for (int i = 0; i < 8; i++) {
                rootNodeArcSS[i] = new DefaultMutableTreeNode("    " + i);
                jTreeForArcSS[i] = new JTree(rootNodeArcSS); // create le 8 roots
    // assignIconsToRootInTheTree(jTreeForArcSS[i]);
    jScrollPane[i] = new JScrollPane();
    jScrollPane[i].setViewportView(jTreeForArcSS[i]); // mette il nodo nel Viewport
    add(jScrollPane[i]); // mette il Viewport nel pannello
    jScrollPane[i].setPreferredSize(treePrefDim);
    // attiva gli ascoltatori ....
    jTreeForArcSS[i].addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    activateDialogXshowTreatments();
    } // for
    fillTrees();
    expandTrees();
    } // costruttore
    private void fillTrees() {
    for (int i = 0; i < treesContents.length; i++) {
    String strNmbr = treesContents[i].substring(treesContents[i].length()-1, treesContents[i].length());
    int nmbr = Integer.parseInt(strNmbr);
    addToothNodeForArcSupSx(nmbr, treesContents[i]);
    private void expandTrees(){
    for (int i = 0; i < 8; i++) {
    jTreeForArcSS[i].expandRow(0);
    * @param toothNmbr
    * @param strTreatment
    private void addToothNodeForArcSupSx(int toothNmbr, String strTreatment) {
    DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(strTreatment); // nuovo treatment da inserire
    DefaultTreeModel model = (DefaultTreeModel) jTreeForArcSS[toothNmbr].getModel();
    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) model.getRoot();
    model.insertNodeInto(newChild, parentNode, 0); // 0 = assegnamo sempre come primo nodo
    assignColorToLeafInTheTree(model);
    } // assingTreatmentToTooth()
    private void assignColorToLeafInTheTree(DefaultTreeModel model) {
    MyCustomizedRendererForJTree renderer = new MyCustomizedRendererForJTree();
    JTree tree = new JTree(model);
    tree.setCellRenderer(renderer);
    } // assignIconsToLeafInTheTree()
    private void activateDialogXshowTreatments() {
    // do anithing
    private void assignIconsToRootInTheTree(JTree jTree) {
    // do nothing now
    } // assignIconsToTree()
    } // class PanelArcSupSx
    class MyCustomizedRendererForJTree extends DefaultTreeCellRenderer {
    @Override
    public Component getTreeCellRendererComponent(
    JTree tree,
    Object value,
    boolean sel,
    boolean expanded,
    boolean leaf,
    int row,
    boolean hasFocus) { // costruttore
    super.getTreeCellRendererComponent(
    tree, value, sel,
    expanded, leaf, row,
    hasFocus);
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
    // String value = (String) val;
    String text = (String) node.getUserObject();
    String prefix = text.substring(0, 1);
    System.out.println("------------------ text = " + text + " prefix = " + prefix);
    // per quanto riguarda il colore ....
    if (prefix.compareTo("*") == 0) {
    setForeground(Color.YELLOW);
    setBackground(Color.YELLOW);
    // System.out.println("colore da usare giallo ");
    } else if (prefix.compareTo("^") == 0) {
    setForeground(Color.BLUE);
    setBackground(Color.BLUE);
    // System.out.println("colore da usare blu ");
    } else {
    setForeground(Color.BLACK);
    setBackground(Color.BLACK);
    // System.out.println("colore da usare bianco ");
    return this;
    } // costruttore

  • Setting the color of a particular node in JTree

    Hi all!
    I'm new to Java and facing a problem with JTrees.
    I'm using the following snippet to create a JTree :
    DeafultMutableTreeNode root = new DefaultMutableTeeNode("Letters");
    DeafultMutableTreeNode parent1 = new DefaultMutableTeeNode("uppercase");
    DeafultMutableTreeNode parent2 = new DefaultMutableTeeNode("lowercase");
    DeafultMutableTreeNode child1 = new DefaultMutableTeeNode("A");
    DeafultMutableTreeNode child2 = new DefaultMutableTeeNode("B");
    DeafultMutableTreeNode child3 = new DefaultMutableTeeNode("C");
    DeafultMutableTreeNode child4 = new DefaultMutableTeeNode("a");
    DeafultMutableTreeNode child5 = new DefaultMutableTeeNode("b");
    DeafultMutableTreeNode child6 = new DefaultMutableTeeNode("c");
    root.add(parent1);
    root.add(parent2);
    parent1.add(child1);
    parent1.add(child2);
    parent1.add(child3);
    parent2.add(child4);
    parent2.add(child5);
    parent2.add(child6);
    JTree tree = new JTree(root);
    JScrollPane pane = new JScrollPane(tree);
    TreePath path = tree.getNextMatch("lowercase", 0, javax.swing.text.Position.Bias.Forward);
    tree.setSelectionPath(path);
    tree.expandPath(path);
    In the above JTree, the node labeled "lowercase" gets selected and expanded as soon as the program is run.
    What i want to know is that, is there any way in which i can set only the "lowercase" node's background to a different color (say, YELLOW) and have it so, no matter if the node is expanded or collapsed or other nodes are expanded or collapsed.
    ps: Sample snippet would really b helpful.

    You need to write your own renderer for this.
    Read the tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display

  • Setting the color of a node in JTree

    Hi all!
    I'm new to Java and facing a problem with JTrees.
    I'm using the following snippet to create a JTree :
    DeafultMutableTreeNode root = new DefaultMutableTeeNode("Letters");
    DeafultMutableTreeNode parent1 = new DefaultMutableTeeNode("uppercase");
    DeafultMutableTreeNode parent2 = new DefaultMutableTeeNode("lowercase");
    DeafultMutableTreeNode child1 = new DefaultMutableTeeNode("A");
    DeafultMutableTreeNode child2 = new DefaultMutableTeeNode("B");
    DeafultMutableTreeNode child3 = new DefaultMutableTeeNode("C");
    DeafultMutableTreeNode child4 = new DefaultMutableTeeNode("a");
    DeafultMutableTreeNode child5 = new DefaultMutableTeeNode("b");
    DeafultMutableTreeNode child6 = new DefaultMutableTeeNode("c");
    root.add(parent1);
    root.add(parent2);
    parent1.add(child1);
    parent1.add(child2);
    parent1.add(child3);
    parent2.add(child4);
    parent2.add(child5);
    parent2.add(child6);
    JTree tree = new JTree(root);
    JScrollPane pane = new JScrollPane(tree);
    TreePath path = tree.getNextMatch("lowercase", 0, javax.swing.text.Position.Bias.Forward);
    tree.setSelectionPath(path);
    tree.expandPath(path);
    In the above JTree, the node labeled "lowercase" gets selected and expanded as soon as the program is run.
    What i want to know is that, is there any way in which i can set only the "lowercase" node's background to a different color (say, YELLOW) and have it so, no matter if the node is expanded or collapsed or other nodes are expanded or collapsed.
    ps: Sample snippet would really b helpful.

    You need to write your own renderer for this.
    Read the tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display

  • Color of visited node in JTree

    I have created a JTree. I know how to change color, icons or background when I click one of the nodes. But the color goes back to the default if I click another node. What I would like to know is how I can keep the color of the node that I have visited (cliked)? For expamle, on a web page, visited links are different color and they don't chagne. Is there any way like this?
    Thanks!

    You can use a TreeCellRenderer to specify the colour or icon or background of a node based on various criteria. See the tutorial on How to Use Trees at http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html for more information about that. If you want the colour to depend on whether you have ever selected the node, then the object you store in the node must be capable of knowing this information. In other words, it must have a setVisited() method, which you call each time the node is selected, and a getVisited() method which you call in your renderer to decide what colour it should be.

  • Is it possible to put two different colors in tree parent node background and child nodes background?

    Is it possible to put two different colors in tree parent
    node background and child nodes background?
    Any help will be very helpful.
    Thanks

    Hi PanosE,
    Yes, you can set up another Standard Edition Server in child domain and then deploy pool pairing.
    You need to deploy a new Front End Pool for the new Standard Edition Server.
    A similar case for your reference.
    https://social.technet.microsoft.com/Forums/office/en-US/eca4299c-8edb-481e-b328-c7deba2a79ba/lync-2013-standard-edition-lync-fe-pools-in-multiple-domain-single-forest-senario?forum=lyncdeploy
    Best regards,
    Eric
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact [email protected]

  • Setting custom color for selected node in JTree?

    Hi,
    i want to set my own color for selected node in JTree. i don't want to set for all the nodes...how to set Color for Selected node using TreeCellRender class?
    Thanks
    Mani

    I assume you are not setting a custom tree cell renderer...
    javax.swing.JTree theTree = ...;
    java.awt.Color newBGColor = ...;
    ((javax.swing.tree.DefaultTreeCellRenderer)theTree.getCellRenderer())
        .setBackgroundSelectionColor(newColor);

  • Different colors for hierarchy nodes in WEBI 4.0 (Possible or not)

    Hi Everyone,
    We have been listening a lot about the capability of Webi 4.0 in terms of Hierarchies from BW BEx Query. It works just fine like in BEx Analyzer, but is it possible to create formatted reports like we do in Crystal reports to display different colors for the hierarchy nodes. The reason for asking about this functionality is though Crystal Enterprise also inherits Hierarchical view from BEx Query we still won't be able to drill down in real time to do some interactive analysis.
    Where as Webi 4.0 can allow us to do interactive analysis by allowing us to drill down on the hierarchies, but it would be great to show the Webi report with different colors for the hierarchy nodes along with the drill down functionality, to give users the best look and feel while working with these reports.
    I am trying to achieve this functionality but I am not successful yet and running out of ideas. I am also not sure if this is possible or not. Can anyone throw some light or share there thoughts on this.
    Any comments will be greatly appreciated.
    Thanks & Regards,
    SRV

    Create a variable with:
         =[Object].Depth
    where [Object] has to be the one containing the BEx hierarchy.
    This function will return the hierarchy level starting with 0 (zero).
    You can use the value of the variable the in the formatting rules:
    variable   equal   [hierarchy level]
    to format all hierarchy nodes on the given level.
    R. Uli

  • Different Icon in a JTree

    Helle mates,
    is it possible to display different icons in a JTree?
    At present, I have the same folder-icons for all folders and the same leaf-icons for each leaf but I want different pics for each folder and for each folder different leaf-icons.
    Is that possible?
    I searched for it but nothing could help me so far. Hopefully, someone got an idea in here.
    Thank you so much

    you need a TreeCellRenderer. it will allow you to draw different icons for different nodes. for example like so:
    public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
      public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        Model model = (Model)((DefaultMutableTreeNode)value).getUserObject();
        setBackgroundNonSelectionColor(model.conditionColor());
        setBackgroundSelectionColor(model.conditionColor().darker());
        setOpenIcon(model.icon());
        setLeafIcon(model.icon());
        setClosedIcon(model.icon());
        Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        if (selected) setForeground(Color.white);
        return c;
    aJTree.setCellRenderer(new MyTreeCellRenderer());
    :thomas

  • How to disable selection of root node in JTree

    Hi all! Thanks for taking a minute to read my post!
    I am writing a really basic JTree for showing a list of items.
    Here is some of the code:
    /** Create a basic tree **/
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Title");
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree tree = new JTree(treeModel);
    /** Method to return the string of the current highlighted selection **/
    public String getSelectionString()
    DefaultMutableTreeNode node =
    tree.getSelectionPath().getLastPathComponent();
    return (String)node.getUserObject();
    I would like to disable selection of the root node of my JTree.
    Thus, if I make a call to getSelectionString() above, it would return null instead of the string that represents the root label.
    I have read the following forum on disabling various TreePaths and TreeNodes in a JTree:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=224691
    This forum suggests implementing the TreeSelectionListener interface and the TreeSelectionModel class and over-riding the addSelectedPath() methods. I tried this suggestion, and I was able to enable and disable the different children of the Jtree, but the root of the JTree would not disable.
    I suppose that I could just simply remove the visibility of the root node, but I really want to avoid that option if possible.
    Wait --- let me be clear ---- I want to disable the selection of the root node only - still allowing selection of all its children.
    Any suggestions?
    Am I missing something really simple here?
    Did I explain my problem clearly?
    Thanks in advance!
    jewels

    simply try this..
    in the
    public void valueChanged(javax.swing.event.TreeSelectionEvent event);
    method of TreeSelectionListener impelentation get the
    TreePath tp = event.getPath();
    from TreePath get the component and then remove the selection from the treePath if it is the node u were checking/root node in this case
    tree.getSelectionModel().removeSelectionPath(tp);
    Try out....

  • Different color of row

    Hi experts,
    I need to change the color the last row of my table with a different color. How can I do this?
    TKS a lot in advance

    HI,
    For coloring your rows follow this approach :
    1.Create a context attirbute for CELL_DESIGN of type WDUI_TABLE_CELL_DESIGN to the node to which the table is bound.
    2. Bind this attribute to the CELL_DEISGN property of all the columns.
    3. Get the no of rows in table.
    4. When last row is selected, change the value of cell design attribue.
    Sample Code :
    lt_table - table with all data which is to be binded with table.
    n - type I.
    lv_tabix - type I.
    ls_table - work area .
    describe lt_table lines n.
    loop at lt_table into ls_table .  "This table is bound to node
    lv_tabix = sy-tabix.
    if lv_tabix = n.
    ls_table-cell_design = CL_WD_TABLE_COLUMN=>E_CELL_DESIGN-BADVALUE_DARK
    modify lt_table from ls_table index lv_index.
    ENDIF.
    endloop. 
    Bind the table to the node.
    For possible values for the color please check http://help.sap.com/saphelp_nw70/helpdata/en/45/0ef14d9d942462e10000000a1553f7/frameset.htm
    This has been discussed many times :
    Refer this thread :
    Re: Color a table row
    Coloring a row in Table Control
    Edited by: Saurav Mago on Oct 8, 2009 9:16 PM

  • Saving "Waveform graph" with cursors, set of different colors, in an image file

    Hello:
    I'm trying to save to a file, a waveform of a "waveform graph" that has cursors, which have different colors. When opening the file I can see that the waves are plotted defined color, but the grids and cursors are colored black.
    Someone can tell me what to do, so that the file is saved with the original colors of the "waveform graph"?
    Best Regards

    Probably this is happening because you are using the Invoke node Image Export, which captures an image with less information. However, if your application allows, using the Invoke Node Get Image, which captures your control, displays all the colors of your waveform, include cursors and grids colors.
    In this link bellow, you can see how use this Invoke Node:
    http://digital.ni.com/public.nsf/allkb/5AE4ADCBB65A6D8F86256FBF007A1AC1?OpenDocument
    I hope this helped you. Success in your application.
    Regards.
    Wesley Rocha
    Applications Engineer
    National Instruments Brazil
    www.ni.com/suporte
    Wesley Rocha
    Application Engineer
    National Instruments Brazil
    Visite a nossa comunidade em PORTUGUÊS!!!

  • I have a question about the calendar on the ipad2. I have multiple calendars in different colors. Some of the events are filled in with color. Others are just listed with a colored dot in front of the event. Any ideas why events ar showing up differently?

    I have an ipad2 and my question is about the calendar. I set up multiple calendars with different colors. Some of the events show up in filled color. Others only show with a colored dot in front of the event. I can't figure out why some show up one way and others show up differently? Any thoughts?

    On mine the ones that show on a coloured background are all-day events, the ones with dots and just timed events.

  • Not able to color different rows with different colors in a column of table

    Hi,
    I am trying to to display different rows with different colors in a column of the table based on some decode condition.
    I have gone through the following threads :
    Can we colour the rows in the column of a table
    Changing Color of a value in a column
    This is what i have done :
    1.Added the following code to custom.xss(changed the name to Custom.xss as suggested in one of the above threads) --- in path ---- jdev\myhtml\OA_HTML\cabo\styles
    <style selector=".1">
    <includeStyle name="DefaultFontFamily"/>
    <property name="font-size">11pt</property>
    <property name="font-weight">Bolder</property>
    <property name="color">#008000</property>
    <property name="text-indent">3px</property>
    </style>
    <style selector=".2">
    <includeStyle name="DefaultFontFamily"/>
    <property name="font-size">11pt</property>
    <property name="font-weight">Bolder</property>
    <property name="color">#FFFF00</property>
    <property name="text-indent">3px</property>
    </style>
    2. Sql query of the VO is :
    select comments,role ,decode(role,'REQUESTER','1','2') Colorattr from xxat_sars_action_history where request_id = :1 and event_name = :2 and action_code <> 'PENDING'
    order by sequence_num desc
    3. Coded the following in the process request of the controller:
    OATableBean table = (OATableBean)webBean.findIndexedChildRecursive("CommentsTB");
    OAMessageStyledTextBean roleBN = (OAMessageStyledTextBean)webBean.findIndexedChildRecursive("role");
    OADataBoundValueViewObject cssjob = new OADataBoundValueViewObject(roleBN,"Colorattr");
    roleBN.setAttributeValue(oracle.cabo.ui.UIConstants.STYLE_CLASS_ATTR, cssjob);
    where 1 and 2 form the colors ( i have even tried with 'Red' and 'Yellow'...as it was not working replaced with 1 and 2)
    4.The query returns data fine with corresponding 1 and 2 values.
    But different colors are not getting reflecting on to the UI.
    I am testing this on my local jdev.
    Please do let me know if i am missing something.
    Thanks ,
    Sushma.

    Any Clues please.....
    Thanks,
    Sushma.

Maybe you are looking for