How to Create JTree in Java Swing

Create JTree in Java Swing

This example program about, How to create JTree in Java swing. The program has been tested and output is shared in the post.

Example Program

package com.dineshkrish.swing;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class JTreeExample {

	public static void main(String[] args) {
		
		// Defining JFrame Object
		JFrame window = new JFrame();
		
		// Configuring the window
		window.setTitle("JTree Example");
		window.setSize(250, 350);
		window.setVisible(true);
		
		// Creating the root element
		DefaultMutableTreeNode  root = new DefaultMutableTreeNode("Vehicle");
		
		// Creating the child nodes
		DefaultMutableTreeNode  child1 = new DefaultMutableTreeNode("Bike");
		DefaultMutableTreeNode  child2 = new DefaultMutableTreeNode("Car");
		
		// Adding the child nodes to root node
		root.add(child1);
		root.add(child2);
		
		// Creating the sub child nodes
		DefaultMutableTreeNode  sub1 = new DefaultMutableTreeNode("Honda");
		DefaultMutableTreeNode  sub2 = new DefaultMutableTreeNode("Bajaj");
		DefaultMutableTreeNode  sub3 = new DefaultMutableTreeNode("Hero");
		

		DefaultMutableTreeNode  sub4 = new DefaultMutableTreeNode("BMW");
		DefaultMutableTreeNode  sub5 = new DefaultMutableTreeNode("Audi");
		DefaultMutableTreeNode  sub6 = new DefaultMutableTreeNode("Mercedes");
		
		// Adding the sub child nodes to child nodes
		child1.add(sub1);
		child1.add(sub2);
		child1.add(sub3);
		
		child2.add(sub4);
		child2.add(sub5);
		child2.add(sub6);
		
		// Defining the JTree object with root node
		JTree tree = new JTree(root);
		
		// Adding the JTree to JFrame
		window.add(tree);
		
	}
}

Output

How to Create JTree in Java Swing

References

1. Java Swing API
2. JFrame API JavaDocs
3. JTree API JavaDocs
4. DefaultMutableTreeNode API JavaDocs

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.