Java Swing - Understanding TreeNode and Creating JTree from DefaultMutableTreeNode [Updated: Feb 16, 2018, Created: Feb 16, 2018] |
|
||
In this tutorial we will create
Understanding TreeNodeA Understanding MutableTreeNodeThis is a subinterface of
ExampleCreating JTreepublic class TreeExampleMain { public static void main(String[] args) { TreeNode projectHierarchyTreeNode = TradingProjectDataService.instance.getProjectHierarchy(); JTree tree = new JTree(projectHierarchyTreeNode); 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; } } Using DefaultMutableTreeNodepublic enum TradingProjectDataService { instance; private final String ROLES[] = {"Project Manager", "Tech Lead", "Developer", "Scrum Master", "Business Analyst"}; private DefaultMutableTreeNode rootNode; TradingProjectDataService() { rootNode = new DefaultMutableTreeNode("Trading Project Modules"); 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) { DefaultMutableTreeNode moduleNode = new DefaultMutableTreeNode(module); rootNode.add(moduleNode); for (String project : projects) { moduleNode.add(getProjectNode(module, project)); } } private MutableTreeNode getProjectNode(String module, String project) { DefaultMutableTreeNode projectNode = new DefaultMutableTreeNode(new Project(project)); for (int i = 0; i < ROLES.length; i++) { projectNode.add(getEmployeeNodeForRole(module, project, ROLES[i])); } return projectNode; } private MutableTreeNode getEmployeeNodeForRole(String module, String project, String role) { //just a random employee for testing ProjectParticipant projectParticipant = new ProjectParticipant(RandomUtil.getFullName(), role); DefaultMutableTreeNode employeeNode = new DefaultMutableTreeNode(projectParticipant); return employeeNode; } public TreeNode getProjectHierarchy() { return rootNode; } } The rest of the classes are same as our last example's classes. OutputOutput is same as our last example's output. Example ProjectDependencies and Technologies Used:
|
|
||
|
|||
|