Introduction
In this section, you will learn to create a horizontal tree in java.
Description of the Program:
This program creates a JTree that contains a root and the nodes.This program implements a class (JTreeHorizontal). Here the init() method creates root and the child nodes through DefaultMutableTreeNode method. These objects are added in the JTree and the putClintProperty() method displays them horizontally in a JTree on the frame.
putclientProperty(Object key, Object val): The clientProperty dictionary is not intended to support large scale extensions to Jcomponent nor should it be considered an alternative to subclassing when designing a new component. It takes following type values:
key: This is the client property key.
val: This is the client
property value.
Here is the code of this program:
import javax.swing.*; import javax.swing.tree.*; import java.awt.*;
public class JTreeHorizontal extends JFrame{ JTree tree;
public JTreeHorizontal(){ super("JTreeHorizontal Frame");
setSize(300, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); }
public void init(){
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode book = new DefaultMutableTreeNode("Book");
DefaultMutableTreeNode javabook = new DefaultMutableTreeNode("Java Book");
DefaultMutableTreeNode jspbook = new DefaultMutableTreeNode("JSP Book");
DefaultMutableTreeNode phpbook = new DefaultMutableTreeNode("PHP Book");
DefaultMutableTreeNode structbook = new DefaultMutableTreeNode("STRUCT Book");
DefaultMutableTreeNode contry = new DefaultMutableTreeNode("CONTRY");
DefaultMutableTreeNode india = new DefaultMutableTreeNode("INDIA");
DefaultMutableTreeNode usa = new DefaultMutableTreeNode("USA");
DefaultTreeModel treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.putClientProperty("JTree.lineStyle", "Horizontal");
treeModel.insertNodeInto(book,root, 0);
treeModel.insertNodeInto(contry,root, 0); book.add(javabook);
book.add(jspbook); book.add(phpbook); book.add(structbook);
contry.add(india); contry.add(usa);
getContentPane().add(tree, BorderLayout.CENTER); }
public static void main(String args[]){
JTreeHorizontal jh = new JTreeHorizontal();
jh.init();
jh.setVisible(true); } }
Output this program:

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Adding Horizontal lines to Group Nodes
Post your Comment