Close

Java Swing - Using custom TreeCellRenderer for JTree

[Updated: Jul 4, 2018, Created: Feb 15, 2018]

Following example shows how to implement custom TreeCellRenderer to customize JTree rendering.

Creating JTree

public class TreeExampleMain {
  public static void main(String[] args) {
      Hashtable<?, ?> projectHierarchy =
              TradingProjectDataService.instance.getProjectHierarchy();
      JTree tree = new JTree(projectHierarchy);
      tree.setCellRenderer(new TradingProjectTreeRenderer());
      JFrame frame = createFrame();
      frame.add(new JScrollPane(tree));
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
  }

  private static JFrame createFrame() {
      JFrame frame = new JFrame("JTree Renderer example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(new Dimension(500, 400));
      return frame;
  }
}

Creating Model

public enum TradingProjectDataService {
  instance;
  private final String ROLES[] =
          {"Project Manager", "Tech Lead", "Developer", "Scrum Master", "Business Analyst"};
  private Hashtable<Object, Object> modules = new Hashtable<>();

  TradingProjectDataService() {
      addModule("Trading", "Real Time Trading", "Order System");
      addModule("Future/Option", "Option Analyzer", "Market Scanning System");
      addModule("Fixed Income", "Bond Tool", "Price/Yield Calculator",
              "Strategy Evaluator");
  }

  private void addModule(String module, String... projects) {
      for (String project : projects) {
          modules.put(module, getProject(module, project));
      }
  }

  private Object getProject(String module, String project) {
      Hashtable<Object, Object> projectMap = new Hashtable<>();
      projectMap.put(new Project(project), getEmployeesForProject(module, project));
      return projectMap;

  }

  private Object getEmployeesForProject(String module, String project) {
      //random example employees, in real app we will get it from backend
      ProjectParticipant[] employees = new ProjectParticipant[ROLES.length];
      for (int i = 0; i < ROLES.length; i++) {
          employees[i] = new ProjectParticipant(RandomUtil.getFullName(), ROLES[i]);
      }
      return employees;
  }

  public Hashtable<?, ?> getProjectHierarchy() {
      return modules;
  }
}
public class ProjectParticipant {
  private final String name;
  private final String role;

  public ProjectParticipant(String name, String role) {
      this.name = name;
      this.role = role;
  }
    .............
}
public class Project {
  private final String name;

  public Project(String name) {
      this.name = name;
  }
    .............
}

Implementing TreeCellRenderer

public class TradingProjectTreeRenderer extends DefaultTreeCellRenderer {
  private static final String SPAN_FORMAT = "<span style='color:%s;'>%s</span>";
  private final ImageIcon employeeIcon;

  public TradingProjectTreeRenderer() {
      employeeIcon = new ImageIcon(TradingProjectTreeRenderer.class.getResource("/images/employee.png"));
  }

  @Override
  public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                                                boolean leaf, int row, boolean hasFocus) {
      super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
      Object userObject = node.getUserObject();
      if (userObject instanceof ProjectParticipant) {
          ProjectParticipant pp = (ProjectParticipant) userObject;
          String text = String.format(SPAN_FORMAT, "blue", pp.getName());
          text += " [" + String.format(SPAN_FORMAT, "orange", pp.getRole()) + "]";
          this.setText("<html>" + text + "</html>");
          this.setIcon(employeeIcon);
      } else if (userObject instanceof Project) {
          Project project = (Project) userObject;
          String text = String.format(SPAN_FORMAT, "green", project.getName());
          this.setText("<html>" + text + "</html>");
      } else {
          String text = String.format(SPAN_FORMAT, "red", userObject);
          this.setText("<html>" + text + "</html>");
      }
      return this;
  }
}

Output

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.3.9

JTree TreeCellRenderer Example Select All Download
  • jtree-renderer-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • TradingProjectTreeRenderer.java
                • util
          • resources
            • images

    See Also