Close

Java Swing - Creating JTree from a Hashtable and listening to selections

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

Following is a basic Jtree example. We will create our JTree from Hashtable. We will also add TreeSelectionListener for listening to node selections.

Creating JTree

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

  private static TreeSelectionListener createTreeSelectionListener() {
      return treeSelectionEvent -> {
          TreePath path = treeSelectionEvent.getPath();
          System.out.println("Path: " + path);
          Object c = path.getLastPathComponent();
          DefaultMutableTreeNode node = (DefaultMutableTreeNode) c;
          System.out.println("User Object: " + node.getUserObject());
          System.out.println("---");
      };
  }

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

Creating Hashtable

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(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
      String[] employees = new String[ROLES.length];
      for (int i = 0; i < ROLES.length; i++) {
          employees[i] = RandomUtil.getFullName() + " [" + ROLES[i] + "]";
      }
      return employees;
  }

  public Hashtable<?, ?> getProjectHierarchy() {
      return modules;
  }
}

Output

On node selection, following output is printed on the console:

Path: [root, Future/Option, Market Scanning System, Claudie Martindale [Developer]]
User Object: Claudie Martindale [Developer]
---
Path: [root, Future/Option, Market Scanning System, Dorinda Hein [Scrum Master]]
User Object: Dorinda Hein [Scrum Master]
---

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.3.9

JTree basic example Select All Download
  • jtree-basic-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • TreeExampleMain.java
                • util

    See Also