简体   繁体   中英

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM