posted 22 years ago
Hi all, I have created a JTree with specific node-icons on each level. For example: The root shows a globe, the children show cities, the leaves show persons,... All in all the tree contains 5 levels of nodes:
root [globe]
|
x-level2 [city]
|
x-level3 [house]
|
x-level4 [family]
|
x-leaf [person]
Everything works fine until I refresh the JTree:
-the city-icon moves to the place of level3-node
-the house-icon moves to the place of level4-node
-the family-icon moves to the place of level2-node
Root and leaf stay as they are, as they are created by a different query than the other nodes.
Has anyone an idea how to solve this problem?
Thanks in advance!
Tom
DefaultMutableTreeNode top = new DefaultMutableTreeNode();
final JTree tree = new JTree(top);
JScrollPane treeView = new JScrollPane(tree);
...
tree.setCellRenderer(new IconRenderer());
...
//Class for setting up the tree icons
class IconRenderer extends DefaultTreeCellRenderer {
ImageIcon globe;
ImageIcon city;
ImageIcon house;
ImageIcon family;
ImageIcon person;
public IconRenderer() {
globe = new ImageIcon("img/globe.gif");
city = new ImageIcon("img/city.gif");
house = new ImageIcon("img/house.gif");
family = new ImageIcon("img/family.gif");
person = new ImageIcon("img/person.gif");
}//end public IconRenderer()...
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);
//Set up city icon
if (checkComponent(value) == 1) {
setIcon(city);
}
//Set up house icon
if (checkComponent(value) == 2) {
setIcon(house);
}
//Set up family icon
if (checkComponent(value) == 3) {
setIcon(family);
}
//Set up person icon
if (leaf) {
setIcon(person);
}
//Set up globe icon
if (row == 0) {
setIcon(globe);
}
return this;
}//end public Component getTreeCellRendererComponent( JTree tree,...
protected int checkComponent(Object value) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
Object nodeInfo = (Object)(node.getUserObject());
TreeNode rootNode = node.getRoot();
TreeNode cityNode = null;
TreeNode houseNode = null;
//rootNode is after refresh == cityNode
for (int i = 0; i <= rootNode.getChildCount() - 1; i++ ) {<br /> cityNode = rootNode.getChildAt(i);<br /> if (nodeInfo.toString() == cityNode.toString()) {<br /> return 1; //=> cityNode
}//end if...
for (int j = 0; j <= cityNode.getChildCount() - 1; j++ ) {<br /> houseNode = cityNode.getChildAt(j);<br /> if (nodeInfo.toString() == houseNode.toString()) {<br /> return 2; //=> houseNode
}//end if...
}//end for (int j = ...
}//end for (int i = ...
return 3; //=> contractNode
}//end protected boolean....
}//end class IconRenderer extends DefaultTreeCellRenderer...