In a nutshell, I want the tree be rendered such that the first level is bold.
public class TreeRenderer1 extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
if (node.getLevel()==1) {
setFont(getFont().deriveFont(Font.BOLD));
}
return this;
}
}
This, however, make all the nodes in my tree bold. What is wrong?
Reset the font state of the render if the level is NOT 1
...
if (node.getLevel()==1) {
setFont(getFont().deriveFont(Font.BOLD));
} else {
setFont(getFont().deriveFont(Font.PLAIN));
}
Render's are a shared resource, any changes you make to it are carried onto the next element to be rendered, so you must always make sure you set it to a "default" state at some point
In your code you set font bold for level 1 but what about the other levels. Where is the else condition? Can you please try this?
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
if (node.getLevel()==1) {
setFont(getFont().deriveFont(Font.BOLD));
} else {
setFont(getFont().deriveFont(Font.PLAIN));
}
return this;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.