Monday , December 11 2017
Home / java / Java Swing JTree Example

Java Swing JTree Example

In this tutorial, we are going to implement Swing JTree. The JTree is a class which is used to display the set of hierarchical data.

Swing JTree Example :

In this example we are going to create a simple swing JTree.


import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

class MyTreeDemo extends JFrame {
    JTree tree;
    DefaultMutableTreeNode root, parent1, parent2, child,child1, child2;

    MyTreeDemo() {
        super("JTree Demo");

        root = new DefaultMutableTreeNode("States");
        parent1 = new DefaultMutableTreeNode("Andhra Pradesh");
        child = new DefaultMutableTreeNode("Vijayawada");
        child1 = new DefaultMutableTreeNode("Vizag");
        parent2 = new DefaultMutableTreeNode("Telangana");
        child2 = new DefaultMutableTreeNode("Hyderabad");

        // Adding child nodes to parent
        parent1.add(child);
        parent1.add(child1);
        parent2.add(child2);
        
        // Adding parent nodes to root
        root.add(parent1);
        root.add(parent2);

        // Adding root to JTree
        tree = new JTree(root);

        getContentPane().add(new JScrollPane(tree));
        setSize(300, 300);
        setVisible(true);
    }
}

class JTreeDemo {
    public static void main(String args[]) throws Exception {
        UIManager
                .setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        new MyTreeDemo();
    }
}

Output :

Swing JTree Example

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

Java Graphics2D Class Example

In this tutorials, we are going to see how to use Java Graphics2D class. Java …

Leave a Reply

Your email address will not be published. Required fields are marked *