JTree

A JTree is a component that presents a hierarchical view of data. The user has the ability to expand or collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class.

The MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child nodes or change the parent node.The DefaultMutableTreeNode class implements the MutableTreeNode interface. It represents a node in a tree. One of its constructors is shown here:

DefaultMutableTreeNode(Object obj)

Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t have a parent or children. To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can be used. Its signature is shown here:

void add(MutableTreeNode child)

Here, child is a mutable tree node that is to be added as a child to the current node.

Program 

dsdsd

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JScrollPane;
import java.awt.Dimension;
import java.awt.FlowLayout;

class Frame extends JFrame {

    Frame()
    {
        setTitle("JTree");
        setLayout(new FlowLayout());
        setJTree();
        setSize(700,350);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    private void setJTree()
    {
        DefaultMutableTreeNode main = new DefaultMutableTreeNode("List of programming languages by type");
        createTree(main);
        JTree jt = new JTree(main);
        JScrollPane js = new JScrollPane(jt);
        js.setPreferredSize(new Dimension(300,300));
        add(js);
    }
 
    private void createTree(DefaultMutableTreeNode main)
    {
        DefaultMutableTreeNode sub1 = new DefaultMutableTreeNode("Assembly languages");
        sub1.add(new DefaultMutableTreeNode("Autocoder"));
        sub1.add(new DefaultMutableTreeNode("Linoleum"));
        sub1.add(new DefaultMutableTreeNode("Sphinx C"));
        DefaultMutableTreeNode sub2 = new DefaultMutableTreeNode("Procedural languages");
        sub2.add(new DefaultMutableTreeNode("C"));
        sub2.add(new DefaultMutableTreeNode("Fortran"));
        sub2.add(new DefaultMutableTreeNode("Pascal"));
        DefaultMutableTreeNode sub3 = new DefaultMutableTreeNode("Object-oriented languages");
        sub3.add(new DefaultMutableTreeNode("C++"));
        sub3.add(new DefaultMutableTreeNode("Java"));
        sub3.add(new DefaultMutableTreeNode("Ruby"));
        main.add(sub1);
        main.add(sub2);
        main.add(sub3);
    }
}

public class Javaapp {
 
    public static void main(String[] args) {
     
       Frame fr = new Frame();
    }
}

Leave a Comment