Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML


 
  
 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 

 
Facing Programming Problem?
Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Displaying Hierarchical data in JTree 

                         

In this section, you will learn to display the hierarchical data in JTree . When you select the hierarchical data it is also displayed on the command prompt.

Program Description:

The following program constructs a tree that displays the hierarchical data. Here CellRenderer class extends JLabel and implements TreeCellRenderer.  It displays the tree node like: File, Subfile and SubNode. The getTreeCellRendererComponent() method sets the value of the current tree cells. If your selection is 'true' (if any node is selected ), the cell is expanded and the selected node is displayed . The StringBuffer class implements a mutable sequence of characters. The TreeSectionListener listens to any change needed for the TreeSeclectionModel. The TreeSectionEvent handles the changes to be made  in the current selection. 

Finally, you get a tree that displays hierarchical data . This tree is displayed on the JFrame.

Here is the code of this program:

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;

public class DisplayingJTreeData {
  class CellRenderer extends JLabel implements TreeCellRenderer {
    CellRenderer(){}
    public Component getTreeCellRendererComponent(JTree tree, Object value,boolean 
          selected, 
boolean expanded, boolean file, int row,boolean hasFocus){   
      StringBuffer buffer = new StringBuffer();
      if (expanded)
        buffer.append("File:");
      if (file)
        buffer.append("Subfile:");
      if (hasFocus)
        buffer.append("SubNode:");
      buffer.append(row + "->");
      buffer.append(value.toString());
      setForeground(selected ? Color.RED : Color.RED);
      setText(buffer.toString());
      return this;
    }
  }
  public DisplayingJTreeData() {
    JFrame frame = new JFrame("Displaying Data Tree frame");
      DefaultMutableTreeNode javaBook = new DefaultMutableTreeNode("JavaBook");
      DefaultMutableTreeNode javaDeveloper = new DefaultMutableTreeNode("JavaDevelopers");
    DefaultMutableTreeNode java = new DefaultMutableTreeNode("Java");
    DefaultMutableTreeNode javaTeamName=new DefaultMutableTreeNode("JavaTeamName");
      javaBook.add(javaDeveloper);
    javaBook.add(javaTeamName);
      String javaTeams[] "Programmer""Coding""Tester""ProjectDesigner  ",
              "ProjectDeveloper"
"ProjectManager""SinearProgramer""JuniarProgramer"};
      for (int i = 0, n = javaTeams.length; i < n; i++)
      javaDeveloper.add(new DefaultMutableTreeNode(javaTeams[i]));
    String teamNames[]={"Amar","Vinod","Chandan","Sushil","Rajesh","Amit","Suman","Santosh"};
    for (int i = 0, n = teamNames.length; i < n; i++)
      javaTeamName.add(new DefaultMutableTreeNode(teamNames[i]));
    javaBook.add(java);
      String bookLabels[] "JavaTutorial""JavaProgram""JavaNews""Java","project",
                                            
"JavaDevelopment"};
    for (int i = 0, n = bookLabels.length; i < n; i++)
        java.add(new DefaultMutableTreeNode(bookLabels[i]));
      JTree tree = new JTree(javaBook);
      tree.addTreeSelectionListener(new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent e) {
        TreePath treepath = e.getPath();
        System.out.println("Java: " + treepath.getLastPathComponent());
        Object elements[] = treepath.getPath();
        for (int i = 0, n = elements.length; i < n; i++) {
          System.out.print("->" + elements[i]);
        }
        System.out.println();
      }
    });
    DefaultMutableTreeNode file = javaBook.getLastLeaf();
    TreePath path = new TreePath(file.getPath());
    tree.setSelectionPath(path);
    tree.setCellRenderer(new CellRenderer());
    JScrollPane scroll = new JScrollPane(tree);
    Container c = frame.getContentPane();
    c.add(scroll, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(350300);
    frame.setVisible(true);
  }
  public static void main(String args[]){
    try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    }
    catch (Exception evt) {}
    new DisplayingJTreeData()
  }
}

Download this program.

Output of the program:

After clicking tree node the message is displayed on the command prompt.

C:\javaswing>javac DisplayingJTreeData.java

C:\javaswing>java DisplayingJTreeData
Java: JavaDevelopment
->JavaBook->Java->JavaDevelopment
Java: Vinod
->JavaBook->JavaTeamName->Vinod
Java: Amit
->JavaBook->JavaTeamName->Amit
Java: JavaProgram
->JavaBook->Java->JavaProgram

 

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Latest Searches:
save image to file
java code to connect t
Checking
File Validation code
how is application of
enterprise portal
disable minimize butto
hast table
advantages of jsp over
Custom Tutorials
removing spaces betwee
struts2 tag
add check box to a jta
Tiles definition richf
column name in panel g
jar entry
PHP Web Traffic Analys
java program to check
ะ�?????ะ�?????
java programm for arra
how to call pl/sql fro
logice
iterator
sleep
S[ring
Photoshop Photo Effect
Image with mouse drag
The JDBC(tm) Universal
Image panel should pro
å???å????å????å???å???
X10 Client and Server
delete data in mysql d
rs.relative
Button
setPropertyActionListe
jQuery To Hide the Div
hibernate many to many
break?ะ�ะ???????
Photoshop Basics Using
Photoshop Drawing Cand
insert column
ASP EXAMPLE' and 1=1 a
line break in javascri
java functions
spring portlet
draw tree
display data from mysq
passing parameters to
CLDC Chechbox example
dynamic table
Account superclass and
close a frame
java cancel button
which design patterns
tiles in structs
Photoshop Basics Draw
JavaScript functions o
partially selected che
java inner class
JavaScript functions
Arrays
html:frame
popup in jsp
c tutorial
ready made component o
Struts1.1
Developing Struts Hibe
Jar files in java
connectivity of ms sql
split
JavaScript
differences of java to
optiontransferselect
using javascripting in
how can we select an d
hibernate2 Tomcat5.5 s
create action listener
FlowLayout
Flex Java Tutorial
rotate
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.