Jarek
Jarek

Reputation: 7729

Rendering nodes in JTree with multiple different fonts

Imagine I have a JTree that is showing multiple strings - for example a list of colors. How it would be possible to render such a tree with different color/font combination? How to implement TreeCellRenderer correctly?

Thank you for help.

Upvotes: 0

Views: 2522

Answers (2)

Mazyod
Mazyod

Reputation: 22569

Another possible way is to make an inner class that implements TreeCellRenderer. All you have to do then is customize the JLabel the way you want.

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

    Component returnValue = null;
    if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
      Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
      if (userObject instanceof Employee) {
        Employee e = (Employee) userObject;
        firstNameLabel.setText(e.firstName);
        lastNameLabel.setText(e.lastName);
        salaryLabel.setText("" + e.salary);
        if (selected) {
          renderer.setBackground(backgroundSelectionColor);
        } else {
          renderer.setBackground(backgroundNonSelectionColor);
        }
        renderer.setEnabled(tree.isEnabled());
        returnValue = renderer;
      }
    }
    if (returnValue == null) {
      returnValue = defaultRenderer.getTreeCellRendererComponent(tree, value, selected, expanded,
          leaf, row, hasFocus);
    }
    return returnValue;
  }

taken from this site.

Upvotes: 1

StanislavL
StanislavL

Reputation: 57421

You can extend DefaultTreeCellRenderer. In the getTreeCellRendererComponent method you call super() and check you conditions e.g. by analysing value. After that call setFont(), setBackground() and setForeground() methods accordingly.

Upvotes: 2

Related Questions