Pages

Simple program to use JTree in Java

This program demonstrate how to use JTree in Java. JTree can be used to display in hierarchical pattern. One of the use of JTree can be used for displaying folders and files. For using we have to use DefaultMutableTreeNode calss for creating node for tree and DefaultTreeModel for creating tree model. The following example gives you some idea about how to use JTree in Java.

Source Code:
import javax.swing.*;
import javax.swing.tree.*;

class JTreeExample extends JFrame{

    JFrame frame;
    JTree tree;
    JScrollPane scrollPane;
    public JTreeExample(){
        super("JTree Example");
        setSize(300,500);
        //root node
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("GCES");
     
        //create node;
        DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Location");
        DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("ESTD");
        DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("Website");
        DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("E-mail");
        DefaultMutableTreeNode node5 = new DefaultMutableTreeNode("Info");
     
        //create subnode and add to node;
        node1.add(new DefaultMutableTreeNode("Lamachaur"));
        node1.add(new DefaultMutableTreeNode("Pokhara"));
        node1.add(new DefaultMutableTreeNode("Nepal"));
        node2.add(new DefaultMutableTreeNode("1998"));
        node3.add(new DefaultMutableTreeNode("www.gces.edu.np"));
        node4.add(new DefaultMutableTreeNode("gces@gces.edu.np"));
        node5.add(new DefaultMutableTreeNode("Software Engineering College"));
     
        //adding node to root;
        root.add(node1);
        root.add(node2);
        root.add(node3);
        root.add(node4);
        root.add(node5);
     
       //creating tree model
       DefaultTreeModel model = new DefaultTreeModel(root);
       tree = new JTree();
       tree.setModel(model);
       scrollPane = new JScrollPane();
       scrollPane.setViewportView(tree);
       add(scrollPane);
    }
}

public class TreeDemo{
    public static void main(String[] args){
        JTreeExample demo = new JTreeExample();
        demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        demo.setVisible(true);
    }
}

Output:

@msucil

Phasellus facilisis convallis metus, ut imperdiet augue auctor nec. Duis at velit id augue lobortis porta. Sed varius, enim accumsan aliquam tincidunt, tortor urna vulputate quam, eget finibus urna est in augue.

No comments:

Post a Comment