SEARCH HERE

Tuesday, December 27, 2022

Java JTree

 

Java JTree

The JTree class is used to display the tree structured data or hierarchical data. JTree is a complex component. It has a 'root node' at the top most which is a parent for all nodes in the tree. It inherits JComponent class.

JTree class declaration

Let's see the declaration for javax.swing.JTree class.

  1. public class JTree extends JComponent implements Scrollable, Accessible  

Commonly used Constructors:

ConstructorDescription
JTree()Creates a JTree with a sample model.
JTree(Object[] value)Creates a JTree with every element of the specified array as the child of a new root node.
JTree(TreeNode root)Creates a JTree with the specified TreeNode as its root, which displays the root node.

Java JTree Example

  1. import javax.swing.*;  
  2. import javax.swing.tree.DefaultMutableTreeNode;  
  3. public class TreeExample {  
  4. JFrame f;  
  5. TreeExample(){  
  6.     f=new JFrame();   
  7.     DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");  
  8.     DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");  
  9.     DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");  
  10.     style.add(color);  
  11.     style.add(font);  
  12.     DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");  
  13.     DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");  
  14.     DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");  
  15.     DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");  
  16.     color.add(red); color.add(blue); color.add(black); color.add(green);      
  17.     JTree jt=new JTree(style);  
  18.     f.add(jt);  
  19.     f.setSize(200,200);  
  20.     f.setVisible(true);  
  21. }  
  22. public static void main(String[] args) {  
  23.     new TreeExample();  
  24. }}  

Output:

JAVA Jtree 1

0 comments:

Post a Comment

C++

AJAVA

C

E-RESOURCES

LKG, UKG Live Worksheets

Top