Pin It

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 :



Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot