Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to create a simple JTree in Java using Java Swing API ?.

Program to demonstrate how to create a simple JTree in Java using Java Swing API ?.

package com.hubberspot.swing.examples;

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

public class JTreeDemo
{
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame frame = new JTreeFrame();
                frame.setTitle("JTree Demo");               
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}


class JTreeFrame extends JFrame
{
    public JTreeFrame()
    {
        setSize(300, 300);

        DefaultMutableTreeNode country = new DefaultMutableTreeNode("India");
        
        DefaultMutableTreeNode state = new DefaultMutableTreeNode("Maharashtra");
        country.add(state);
        
        DefaultMutableTreeNode city = new DefaultMutableTreeNode("Pune");
        state.add(city);
        city = new DefaultMutableTreeNode("Mumbai");
        state.add(city);
        
        state = new DefaultMutableTreeNode("Madhya Pradesh");
        country.add(state);
        city = new DefaultMutableTreeNode("Indore");
        state.add(city);
        city = new DefaultMutableTreeNode("Bhopal");
        state.add(city);
        
        state = new DefaultMutableTreeNode("Gujrat");
        country.add(state);
        
        city = new DefaultMutableTreeNode("Ahmedabad");
        state.add(city);

        JTree tree = new JTree(country);
        add(new JScrollPane(tree));
    }
}



Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot