Swing: How can I use JTree with JTextPanes as nodes?

JTreeuses DefaultTreeCellRendereras a means of visualizing cells.
This class is a subclass JLabel.

I want to use JTreewith more complex elements than JLabel, for example JTextPane.

The problem is this: I cannot subclass DefaultTreeCellRendererbecause it will still be JLabel.

Writing your own is TreeCellRenderertoo complicated.
What for? Because: it DefaultTreeCellRendererhas 17 fields, and does much more than just implementation TreeCellRenderer. getTreeCellRendererComponent(...).

What simple solution can you develop?

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

+3
source share
2 answers
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 do not need to be as complicated as the default implementation. Subclassing Renedere under JTextPanewill facilitate the implementation of the method.

+1
source

You can still subclass DefaultTreeCellRenderer and override only the method getTreeCellRendererComponentto return the component JTextPaneformatted as you would like. You still have to do a lot of things that DefaultTreeCellRenderer does in its implementation, but you don’t have to worry about servicing these 17 or so fields.

edit removed JTextField editor's solution after reading comments

0

Source: https://habr.com/ru/post/1711941/


All Articles