Home Java Example Java Swing Traverse JTree Example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Traverse JTree Example

Advertisement
In this section, you will read about traversal of a tree and its node .Teaches, displaying the node and its path on the command prompt.

Traverse JTree  Example

     

In this section, you will read about traversal of a  tree and its node .Teaches, displaying the node and its path on the command prompt. The Javax.swing.JTree class is a powerful swing component to display data in a tree structure. 

Program Description:

This program creates a tree with root and child nodes on the frame. The TreeModel is a simple tree data model that uses TreeNodes. The TreeSelectionListener  class performs an action when you click the node of tree. This uses getSelectionPath() method for getting the first path in the selection of node in a tree. Finally, this program performs the selection of a node of the tree to be displayed like the name of tree and its path.

getSelectionPath(): 
This is the method that returns the first path of the selected tree.

Here is the code of this program:

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

public class JTreeTraverse {
  public static void main(String args[]) {
  JFrame fm = new JFrame("JTree Traverse frame");
  String object[] "Cricket""Hokey""Football" };
  JTree tree = new JTree(object);
  tree.setRootVisible(true);
  TreeModel treemodel = tree.getModel();
  Object TraverseObject = treemodel.getRoot();
  if ((TraverseObject != null&& (TraverseObject instanceof 
   DefaultMutableTreeNode
)) {
  TreeSelectionListener treeListener = new TreeSelectionListener() {
  public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
  JTree tree = (JTreetreeSelectionEvent.getSource();
  TreePath object = tree.getSelectionPath();
  System.out.println(object);
  System.out.println(object.getPath());
  }
  };
  tree.addTreeSelectionListener(treeListener);
  JScrollPane scroll = new JScrollPane(tree);
  fm.getContentPane().add(scroll, BorderLayout.CENTER);
  fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  fm.setSize(200200);
  fm.setVisible(true);
  }
  }
}
 

Download this program.

Output of this program:

After click tree node the command prompt will dispaly: 

C:\javaswing>java JTreeTraverse
[root, Hokey]
[Ljava.lang.Object;@5afd29
[root]
[Ljava.lang.Object;@b09e89
[root, Hokey]
[Ljava.lang.Object;@1bf6770
Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 30, 2007

Ask Questions?    Discuss: Traverse JTree Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Mohammad Faisal
November 14, 2011
Exception/Error

When I'm trying to close the root then there is some exception/error. Why?
DMCA.com