participate


Swing - Ho to set different color to different Jtree Nodes
This question is answered.

<<   Back to Forum  |   Give us Feedback
This topic has 8 replies on 1 page.
tonyMrsangelo
Posts:175
Registered: 8/6/07
Ho to set different color to different Jtree Nodes   
Nov 5, 2009 10:09 PM
 
 
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.
 
kevinaworkman
Posts:1,305
Registered: 3/30/09
Re: Ho to set different color to different Jtree Nodes   
Nov 6, 2009 5:56 AM (reply 1 of 8)  (In reply to original post )
 
 
This tells you how to create a custom renderer.
 
tonyMrsangelo
Posts:175
Registered: 8/6/07
Re: Ho to set different color to different Jtree Nodes   
Nov 7, 2009 8:35 AM (reply 2 of 8)  (In reply to #1 )
 
 
I realized this code to assign a custom render to nodes of a JTree in order to change the color
depending from an information, but it doesn't work

private void addToothNodeForArcSupSx(int toothNmbr, String strTreatment) {
//        JTree root = panelArcSupSx.jTreeForArcSS[toothNmbr];  //erro
        DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(strTreatment); // nuovo treatment da inserire
          //
        JTree dummyTree = new JTree(newChild);
        dummyTree.setCellRenderer(new MyCustomizedRendererForJTree(strTreatment));
        //
        DefaultTreeModel model = (DefaultTreeModel) panelArcSupSx.jTreeForArcSS[7 - toothNmbr].getModel();
        DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) model.getRoot();
        // ---------
        model.insertNodeInto(newChild, parentNode, 0); // 0 = assegnamo sempre come primo nodo
        panelArcSupSx.validate();
        panelArcSupSx.repaint();
    } // assingTreatmentToTooth()


where the class that customize the renderer is


class MyCustomizedRendererForJTree extends DefaultTreeCellRenderer {
 
    String category;
 
    public MyCustomizedRendererForJTree(String categ) {
        category = categ;
    }
 
    @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);
        String prefix = category.substring(0, 1);
        DefaultTreeCellRenderer renderer =
                new DefaultTreeCellRenderer();
 
        Color color = null;
        if (prefix.compareTo("*") == 0) {
            color = Color.yellow;
            System.out.println("color to use is yallowo ");
        } else if (prefix.compareTo("^") == 0) {
            color = Color.blue;
            System.out.println("color to use is blue ");
        } else {
            color = Color.white;
            System.out.println("color to use is white ");
        }
 
        renderer.setBackground(color);
        renderer.setForeground(color);
        renderer.setBorderSelectionColor(color);
        renderer.setBackgroundNonSelectionColor(color);
 
//        return renderer;
        return this;
    } // constructor
}


I read the documentation, and in my opinion it should be good....
someone could help me to correct it ?

thank you
regards
tonyMrsangelo
 
tonyMrsangelo
Posts:175
Registered: 8/6/07
Re: Ho to set different color to different Jtree Nodes   
Nov 9, 2009 12:20 AM (reply 3 of 8)  (In reply to #2 )
 
 
I am having troubles with this problem...

I need to change color to String for some nodes in a JTree
To do it I followed an example in the book of Cay Horstmann: (ClassTree in the cap 6 of the second volume).

I tested the code of example and it works good..,
but as well I wrote the same code in my application there it doesn't work..

I write here the code .....

    private void assignColorToLeafInTheTree(DefaultTreeModel modelOfThisNode) {
    
        JTree tree = new JTree(modelOfThisNode);
        MyCustomizedRendererForJTree renderer = new MyCustomizedRendererForJTree();
        tree.setCellRenderer(renderer);
 
    } // assignColorToLeafInTheTree()





class MyCustomizedRendererForJTree extends DefaultTreeCellRenderer {
 
    @Override
    public Component getTreeCellRendererComponent(
            JTree tree,
            Object value,
            boolean sel,
            boolean expanded,
            boolean leaf,
            int row,
            boolean hasFocus) { // constructor
 
        super.getTreeCellRendererComponent(
                tree, value, sel,
                expanded, leaf, row,
                hasFocus);
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
        String text = (String) node.getUserObject();
 
        String prefix = text.substring(0, 1);
        System.out.println("------------------ text = " + text + " prefix = " + prefix);
 
        if (prefix.compareTo("*") == 0) {
            setForeground(Color.YELLOW);
            setBackground(Color.YELLOW);
//            System.out.println("color to use is yellow ");
        } else if (prefix.compareTo("^") == 0) {
            setForeground(Color.BLUE);
            setBackground(Color.BLUE);
//            System.out.println("color to use is blu ");
        } else {
            setForeground(Color.BLACK);
            setBackground(Color.BLACK);
//            System.out.println("color to use is white ");
        }
        return this;
    } /// constructor
}


I should like have an help to know what is wrong....
thank you
regards
tonyMrsangelo
 
jduprez
Posts:1,169
Registered: 10/2/98
Re: Ho to set different color to different Jtree Nodes   
Nov 9, 2009 1:47 AM (reply 4 of 8)  (In reply to #3 )
 
 
It is not clear what you are doing, and at which point you are with this problem...

The code extract in the OP suggests that for each category, you did set a renderer with a specific color. As the JTree has only one renderer, the last one that was set would win.

Kevin then pointed you to the tutorial chapter about customizing JTree rendering. You didn't comment whether you had read and understood it, I feel forced to advise you to have a second look at it.

Then the code extract in post #2 makes no sense: you are creating a dummyTree, and setting the renderer on it, but you do nothing else with this dummyTree: it's not added into a container, nor returned so that the caller code can add it to a container. Indeed the JTree instance pointed to by the dummyTree variable is lost for good when the addToothNodeForArcSupSx() method returns.

The code extract in post #3 has the same problem.

I assume you want to spare us from reading the whole code, so you give us only extracts of code you deem relevant: that is not the proper way to address this issue. The proper way would be to provide an SSCCE of the problem, that is, code where you have trimmed down anything that does not participate into reproducing the problem, but that contains everything to reproduce it (including: that compiles) and that fits within one post (preferrably one class).
The very good property of an SSCCE is that by reducing gradually the problem to only the bare minimum, you often discover (without even having to submit it) where the problem lies. So have a go really, if this problem matters to you.
 
tonyMrsangelo
Posts:175
Registered: 8/6/07
Re: Ho to set different color to different Jtree Nodes   
Nov 9, 2009 8:53 AM (reply 5 of 8)  (In reply to #3 )
 
 
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[i]); // 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
}
 
tonyMrsangelo
Posts:175
Registered: 8/6/07
Re: Ho to set different color to different Jtree Nodes   
Nov 9, 2009 9:26 AM (reply 6 of 8)  (In reply to #5 )
 
 
Hi jduprez ,

The code extract in the OP suggests that for each category, you did set a renderer with a specific color. 
As the JTree has only one renderer, the last one that was set would win.


I red in the book of Cay Horstmann (Core Java 2: Advanced Features cop 6 pg 362)

There is wrote:
It is possible personalize the display of tree in 3 ways:
- it is possible to modify icon font and color ..
- it is possible install a renderer that extend the class DefaultTreeCellRenderer and modify icons, font..
- it is possible to install a renderer that implements the interface TreeCellRenderer in order to design
an personalized image for each node...

What i made is to reproduce the example Classree described in the book that I saw it work ...
but I was not abble to reproduce it in my program...

regards
 
jduprez
Posts:1,169
Registered: 10/2/98
Re: Ho to set different color to different Jtree Nodes   
Nov 10, 2009 2:02 AM (reply 7 of 8)  (In reply to #5 )
 
 
Same mistake as in posts #2 and #3: you set the renderer on a new JTree whose lifetime does not exceed the assignColorToLeafInTheTree(...) method. But you don't set the renderer on the JTrees that matter (those that are created and added to the widget hierarchy in the constructor PanelArcSupSx()).

Instead I modified your method as follow:
public PanelArcSupSx() { // costruttore
        ...
        for (int i = 0; i < 8; i++) {
            rootNodeArcSS[i] = new DefaultMutableTreeNode("    " + i);
            jTreeForArcSS[i] = new JTree(rootNodeArcSS[i]); // create le 8 roots
            assignColorToLeafInTheTree(jTreeForArcSS[i]);
            ...
    }
 
    private void assignColorToLeafInTheTree(JTree tree) {
        MyCustomizedRendererForJTree renderer = new MyCustomizedRendererForJTree();
        tree.setCellRenderer(renderer);
    }


And the tree nodes are appropriately colored (well at least, they are colored).

I want to emphasize, however, that you probably need to deepen your Java language (not Swing) knowledge, especially the part on local variables vs attributes, references vs object,...
Good luck with Swing.
 
tonyMrsangelo
Posts:175
Registered: 8/6/07
Re: Ho to set different color to different Jtree Nodes   
Nov 10, 2009 5:11 AM (reply 8 of 8)  (In reply to #7 )
 
 
hi jduprez ,

you are right,

I was not able to see the mistake....

You were very kind, and really helped me... I tank you very much.

regards
tonyMrsangelo
 
This topic has 8 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums