Create A JTree In Java Eclipse

The Java JTree class is usually used to display a tree structured data or a hierarchical structured data.

Of course in a hierarchical structured data, it has a “head” or a top data or a “root”. And in JTree it has a “root node” at the top of the tree data. That is usually the parent for all nodes inside the tree.

Let’s take a look at the code:

import javax.swing.*;  
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {

JFrame f;

TreeExample(){

f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");

Style.add(font);
Style.add(font);

  DefaultMutableTreeNode tahoma=new DefaultMutableTreeNode("tahoma");
  DefaultMutableTreeNode calibri=new DefaultMutableTreeNode("calibri");
DefaultMutableTreeNode comicSans=new DefaultMutableTreeNode("comic sans");

  DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
  DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
  DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
  DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
  DefaultMutableTreeNode white=new DefaultMutableTreeNode("white");

  color.add(red);
  color.add(blue);
  color.add(green);
  color.add(black);
  color.add(white);

  font.add(tahoma);
  font.add(calibri);
  font.add(comicSans);

  JTree jt=new JTree(style);
  f.add(jt);
  f.setSize(200,260);
  f.setVisible(true);
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TreeExample();
}}

Here’s an image on what you should get :

java jtree

Published by

Rafif Santika

The programming language that I specialize in is Java, because I think Java programming language is more universal and of course because I like it regardless of any reason.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.