I would like to have a JTree component whose leaves may be icons, for
example. The standard TreeCellRenderer is only able to render text,
though.
How can I add icons to be displayed instead or together with text (not the
file/folder icons).
I tried to write my own TreeCellRenderer class that extends a JLabel, but
it didn't work. Basically, I suppose this might be done using the user
object property, but I could not figure out how exactly to do it?
Has anybody done this, yet.
Please, let me know.
Thanks a lot for your help
Andre
--
=======================================================================
Andre Meyer MultiMedia Lab "The Pen is Mightier than the Sword"
Department of Computer Science University of Zurich Switzerland
<mailto:me...@acm.org> <http://www.ifi.unizh.ch/~ameyer>
=======================================================================
Try this example.
class MyTreeCellRenderer extends JLabel implements TreeCellRenderer {
Icon _image;
Icon _selectedImage;
boolean _selected;
JTree _tree;
public Component getTreeCellRendererComponent(JTree tree, Object
value,
boolean selected,
boolean expanded,
boolean leaf, int
row, boolean hasFocus) {
Object nodeObject;
if (value instanceof DefaultMutableTreeNode) {
nodeObject =
((DefaultMutableTreeNode)value).getUserObject();
if (nodeObject instanceof JLabel) {
JLabel label = (JLabel)nodeObject;
nodeObject = label.getText();
_image = label.getIcon();
_selectedImage = label.getSelectedIcon();
}
}
else nodeObject = value;
String stringValue = tree.convertValueToText(nodeObject, selected,
expanded, leaf,
row, hasFocus);
setText(stringValue);
if (selected) {
setIcon(_selectedImage);
setForeground(SystemColor.textHighlightText);
}
else {
setIcon(_image);
setForeground(Color.black);
}
_selected = selected;
_tree = tree;
return this;
}
public void paint(Graphics g) {
Color bColor;
Icon currentI = getIcon();
if(_selected) {
if(currentI != null && getText() != null) {
int offset = (currentI.getIconWidth() + getIconTextGap());
g.setColor(SystemColor.textHighlight);
g.fillRect(offset, 0, getWidth() + 2 - offset, getHeight()
+ 2);
if (_tree == Util.getWindow(_tree).getFocusOwner()) {
g.setColor(Color.yellow);
g.drawRect(offset, 0, getWidth() - 1 - offset,
getHeight() - 1);
}
}
}
super.paint(g);