JTree in Java

  JTree Tutorial in Java


JTree class is used to create a hierarchical view of data, with one top main root node, its sub-root nodes and their children nodes. The user can expand or collapse the top main root node and its sub-root nodes. If a node doesn't have any children node, it is called a leaf node.

The node is represented in Swing API as TreeNode which is an interface. The interface MutableTreeNode extends this interface which represents a mutable node. Swing API provides an implementation of this interface in the form of DefaultMutableTreeNode class.


Declaration:

Public class JTree extends JComponent implements Scrollable, Accessible ;

How to create a node?

To create a simple node following syntax is used:
 DefaultMutableTreeNode red=new DefaultMutableTreeNode("node name") ;

How to make a node CHILD and PARENT?

When we create a node using the above mention line a node is creted on that time .Suppose I created a following nodes

DefaultMutableTreeNode Notes=new DefaultMutableTreeNode("Notes");
DefaultMutableTreeNode Java=new DefaultMutableTreeNode("Java");

If I want to make this node parent then I can use add() method by the following way:-
Notes.add(Java);   // Parent Node.add(Child Node)
When we do this, Notes will became parent node and Java will became child node.

Constructors of JTree:-




Constructor
Description
public JTable()
Creates a JTree with a sample model.
public JTree(TreeModel newModel)
Creates a JTree using TreeModel.
public JTree(TreeNode root)
Creates a JTree with the specified TreeNode as its root.



// Program to illustrate the use of JTree in Java.
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class treeexample {
    JFrame f=new JFrame();
    treeexample()
    {
        f=new JFrame("Tree");
        DefaultMutableTreeNode Notes=new DefaultMutableTreeNode("Notes");
        DefaultMutableTreeNode Java=new DefaultMutableTreeNode("Java");
        DefaultMutableTreeNode AWT=new DefaultMutableTreeNode("AWT");
        DefaultMutableTreeNode Swing=new DefaultMutableTreeNode("Swing");
        DefaultMutableTreeNode Event=new DefaultMutableTreeNode("Event Handling");
        DefaultMutableTreeNode JSP=new DefaultMutableTreeNode("JSP");
        DefaultMutableTreeNode DWH=new DefaultMutableTreeNode("DWH");
        Notes.add(Java);
        Notes.add(DWH);
        Java.add(AWT);
        Java.add(Swing);
        Java.add(Event);
        Java.add(JSP);
        JTree obj=new JTree(Notes);
        f.add(obj);
        f.setSize(600,600);
        f.setVisible(true);
    }
    public static void main(String args[])

     {
        new treeexample();
      }
   

Output :













                                    for any query feel free to comment.





Comments