Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

JTree with icons or other objects

1 view
Skip to first unread message

Andre Meyer

unread,
May 26, 1998, 3:00:00 AM5/26/98
to

Hi

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>
=======================================================================

Vaithilingam Senthil

unread,
May 26, 1998, 3:00:00 AM5/26/98
to Andre Meyer

Create a TreeCellRender class extending a JLabel. Set the icon you want
to be displayed in the label. If you want highlighting then use your own
paint method in this class.

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);

0 new messages