Concept of JTREE in Java

JTree class in java is a swing component and used to arrange the tree-structured data or hierarchical data. It is a complex component and has a root node an also called a parent node in the tree which is the top of all the nodes.A. node can have many children nodes if a node doesn't,t have any children node, it is called a leaf node. It inherits all the JComponent class.

Commonly used Constructors in java are:-

  • JTree()
  • JTree(Object[] value)
  • JTree(TreeNode root)

Example:-

package net.codejava.swing;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample extends JFrame
{
    private JTree tree;
    public TreeExample()
    {
        //create the font node
        DefaultMutableTreeNode font = new DefaultMutableTreeNode("font");

        //create the child nodes
        DefaultMutableTreeNode Times New RomanNode = new DefaultMutableTreeNode("Times New Roman");
        DefaultMutableTreeNode BodoniNode = new DefaultMutableTreeNode("Bodoni");
        DefaultMutableTreeNode GaramondNode = new DefaultMutableTreeNode("Garamond");
        DefaultMutableTreeNode MinionWebNode = new DefaultMutableTreeNode("Minion Web");
        DefaultMutableTreeNode ITCStoneSerifNode = new DefaultMutableTreeNode("ITC Stone Serif");

        //add the child nodes to the font node
         font.add(Times New RomanNode);
         font.add(BodoniNode);
         font.add(GaramondNode);
         font.add(MinionWebNode);
         font.add(ITCStoneSerifNode);
         
        //create the tree by passing in the font node
        tree = new JTree(font);
        add(tree);
         
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("JTree Example");       
        this.pack();
        this.setVisible(true);
    }
     
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TreeExample();
            }
        });
    }       
}

 

Keywords: