views:

249

answers:

2

JTree uses DefaultTreeCellRenderer as cell renderer.
This class is a subclass of JLabel.

I want to use JTree with more complex elements than JLabel, such as JTextPane.

Problem is: I can't subclass DefaultTreeCellRenderer, because it would still be a JLabel.

Writing an own TreeCellRenderer is too complex.
Why? Because: DefaultTreeCellRenderer has 17 fields, and does much more than just implementing TreeCellRenderer's getTreeCellRendererComponent(...).

What simple solution can you devise?

I need the tree elements to be JTextPanes to be able to perform complex formatting.

A: 

You could still subclass DefaultTreeCellRenderer and override just the getTreeCellRendererComponent method to return the JTextPane component formatted as you would like it. You would still need to do a lot of the stuff that DefaultTreeCellRenderer does in its implementation, but you would not have to bother with the maintenance aspect of those 17 or so fields.

edit removed the JTextField editor solution after reading comments

akf
No, that's cell editor. For this, there is a nice abstract class AbstractCellEditor
ivan_ivanovich_ivanoff
+1  A: 
public class JTextPaneTreeCellRenderer extends JTextPane implements TreeCellRenderer {

Method:

public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {

    // do stuff to this instance of JTextPane
    setEditable(selected);
    setText(value.toString()); //Assumes whatever you stuck in the tree has pretty toString

    if (leaf)
        setBackgroundColor(Color.RED);
    return this;
}

You don't need to be as complex as the default implementation. Making the Renedere a subclass of JTextPane will make the implementation of the method much easier.

jjnguy
you could also argue that it would also be 'cleaner' to do it this way.
akf