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:
privatevoid 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...
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 .....
privatevoid 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 ");
} elseif (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 ");
}
returnthis;
} /// constructor
}
I should like have an help to know what is wrong....
thank you
regards
tonyMrsangelo
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.
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;
/**
*
*
*/
publicclass SSCCE_ForPeriodontalCharting extends JFrame {
PanelArcSupSx panelArcSupSx;//
public SSCCE_ForPeriodontalCharting() {
panelArcSupSx = new PanelArcSupSx();
add(panelArcSupSx);
setSize(900, 300);
setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
publicstaticvoid 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() {
publicvoid valueChanged(TreeSelectionEvent e) {
activateDialogXshowTreatments();
}
});
} // for
fillTrees();
expandTrees();
} // costruttore
privatevoid 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]);
}
}
privatevoid expandTrees(){
for (int i = 0; i < 8; i++) {
jTreeForArcSS[i].expandRow(0);
}
}
/**
*
*
* @param toothNmbr
* @param strTreatment
*/
privatevoid 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()
privatevoid assignColorToLeafInTheTree(DefaultTreeModel model) {
MyCustomizedRendererForJTree renderer = new MyCustomizedRendererForJTree();
JTree tree = new JTree(model);
tree.setCellRenderer(renderer);
} // assignIconsToLeafInTheTree()
privatevoid activateDialogXshowTreatments() {
// do anithing
}
privatevoid 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 ");
} elseif (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 ");
}
returnthis;
} // costruttore
}
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...
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]);
...
}
privatevoid 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.