Displayed nodes in a JTree

Hi, i'm creating a JTree with TreeModel, and make the root as my c: drive. when the tree displayed, i found that it display some files that are actually not available in my c: drive. so, can anyone please tell me what's wrong in this case? thanks in advance!

OK, these are two java files, please check for me. Thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
public class MyTree extends JFrame implements ActionListener{
File[] rt;
File drive;
private DefaultComboBoxModel comboModel;
MyTreeModel model;
File root = null;
JTree tree;
    public MyTree() {
        initComponents();
public void initComponents() {
setLayout(new BorderLayout());
  setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
panelB = new javax.swing.JPanel();
panelB.setLayout(new BorderLayout());
comboModel = new DefaultComboBoxModel();
selectDrive = new JComboBox(comboModel);
rt=File.listRoots();
  for (int i=0; i<rt.length; i++)
       drive = rt;
     comboModel.addElement(drive);
selectDrive.setModel(comboModel);
selectDrive.addActionListener(this);
selectDrive.setActionCommand("sel_drive");
tree = new JTree();
tscrollPane = new JScrollPane(tree);
displayTree();
panelB.add(selectDrive,BorderLayout.NORTH);
panelB.add(tscrollPane,BorderLayout.CENTER);
add(panelB,BorderLayout.NORTH);
pack();
public void actionPerformed(ActionEvent e) {
     String cmd = e.getActionCommand();
     if(cmd.equals("sel_drive")){
               displayTree();     
public void displayTree(){
     Object obj = comboModel.getSelectedItem();
     String str = obj.toString();
     File f = new File(str);
     model = new MyTreeModel(f);
     tree.setModel(model);
public static void main(String args[]){
     MyTree treefr = new MyTree();
     treefr.setSize(500, 500);
     treefr.setVisible(true);
public JComboBox selectDrive;
public JPanel panelB;
public JScrollPane tscrollPane;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.io.*;
class MyTreeModel implements TreeModel {
public File root;
public MyTreeModel(File rt) {
     root = rt;
public Object getRoot() {
     return root;
public boolean isLeaf(Object node) { 
     File leaf = (File)node;
     return leaf.isFile();      
public int getChildCount(Object parent) {
     File p = (File)parent;
     if(p.isDirectory()){
          System.out.println("Total Files="+p.list().length);
          return p.list().length;
     }else{
          return 0;
public Object getChild(Object parent, int index) {
File p = (File)parent;
String[] children = p.list();
File child = new File(p,children[index]);
try
     return child;
catch (ArrayIndexOutOfBoundsException e)
e.printStackTrace();
return null;
public int getIndexOfChild(Object parent, Object child) {
String cname;
String[] children = ((File)parent).list();
if (children.length>0){
     cname = ((File)child).getName();
     for(int i = 0; i < children.length; i++) {
     if (cname.equals(children[i]))
          return i;
else{
          return -1;
return -1;
public void valueForPathChanged(TreePath path, Object newvalue) {}
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}

Similar Messages

  • Displaying nodes in a JTree with different icons

    Please can you help me? I have set up a JTree that handles different icons for each item in the tree. The items are all independent and there is no way of grouping them together, so to get around the problem of displaying them in the tree I have stored them in array of images, such that each row in the tree maps to the correct element of the tree (or so I thought).
    However, my overridden version of getTreeCellRendererComponent() displays interesting behaviour. If one of the branches in tree is collapsed, then the number of rows displayed in the tree differs from when it is expanded. This renders my use of an array useless because it doesn't map to what I thought was the structure of the tree and my icons do not align to the correct textual information.
    How can I map my images to the tree so that it displays correctly when the branches are expanded or collapsed?

    You need to be able to figure out what icon to display based on the object that the tree cell is rendering. In other words, the object should have an attribute that you can query that tells your cell renderer what icon to use. If all else fails, change your object to contain a reference to the icon that should be displayed next to it.

  • How do I control the order in which JTree displays nodes?

    I'm trying to display the nodes in a JTree in a specific fashion, but I can't figure out how to change the order JTree displays them in. It seems the default is alphabetically, with leaves first and nodes with children second. I've spent a few hours pouring through the documentation, but I haven't been able to find out what I need to do. Anyone know?

    They are displayed in the order they are added on the same level.

  • JTree first displayed node

    Hi,
    I was looking at JTree API and I find a difference between viewable and displayed nodes: a viewable node is a child of an expanded node, and a displayed node is a viewable one that is indeed displayed in the screen (it falls in the tree visible area).
    Now I want to know the first displayed node in the tree, but I don't see how to obtain it.
    Any help would be appreciated.

    Thanks, tjacobs.
    I tried it but it is difficult to determine it this way.
    I have a JScrollPane; then I try this:
    int x = 50;
    int y = getVerticalScrollBar().getValue() + 5;
    TreePath firstPath = _tree.getPathForLocation(x, y);x = 50 is an attempt to know where the child is; as long as the tree gets expanded, it is greater, but I don't know at which level the tree is expanded in that location.
    Any ideas?

  • How to get total number of nodes in a JTree?

    Hi,
    I am trying to get total number of nodes in a JTree, and cannot find a way to do it.
    The current getRowCount() method returns the number of rows that are currently being displayed.
    Is there a way to do this or I am missing something?
    thanks,

    How many nodes does this tree have?
    import java.awt.EventQueue;
    import javax.swing.*;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.*;
    public class BigTree {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    TreeModel model = new TreeModel() {
                        private String node = "Node!";
                        @Override
                        public void valueForPathChanged(TreePath path,
                                Object newValue) {
                            // not mutable
                        @Override
                        public void removeTreeModelListener(TreeModelListener l) {
                            // not mutable
                        @Override
                        public boolean isLeaf(Object node) {
                            return false;
                        @Override
                        public Object getRoot() {
                            return node;
                        @Override
                        public int getIndexOfChild(Object parent, Object child) {
                            return child == node ? 0 : -1;
                        @Override
                        public int getChildCount(Object parent) {
                            return 1;
                        @Override
                        public Object getChild(Object parent, int index) {
                            return node;
                        @Override
                        public void addTreeModelListener(TreeModelListener l) {
                            // not mutable
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().add(new JScrollPane(new JTree(model)));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    }But for bounded tree model using DefaultMutableTreeNode look at bread/depth/preorder enumeration methods to walk the entire tree. Or look at the source code for those and adapt them to work with the TreeModel interface.

  • How to use custom nodes in a JTree without reinventing the wheel?

    Hello,
    Each node contains two JTextAreas in a Box layout and a few JButtons.
    I wish to display these nodes in a JTree.
    Reading the tutorial, it seems I would have to reimplement the TreeModel, TreeCellRenderer/Editor, MutableTreeNode interfaces etc.
    Can I use the DefaultTreeModel, and other standard widgets (great stuff!) to minimize the amount of reimplementation I must do. aka avoid reinventing the wheel? I was thinking of extending my node from the DefaultMutableTreeNode class - however it does not display the nodes with the TextAreas, buttons etc.
    any help appreciated.
    thanks,
    Anil

    was able to fix it over here:
    http://forum.java.sun.com/thread.jspa?messageID=4089777

  • Can the name of a specific node in a JTree be returned by MouseEvent?

    I have created a mouseListener for a JTree. When a node in the JTree is clicked it should display the name of the node in a JOptionPane. Currently, I have the following:
    tree.addMouseListener(new MouseAdapter()
    public void mouseClicked(MouseEvent me)
         if(me.getClickCount() % 2 == 0)
         String s = "Blank";
         s = (me.getSource()).toString();
         JOptionPane.showMessageDialog(null, "Double clicked "+ s, "two", JOptionPane.PLAIN_MESSAGE);               
    }//mouseClicked          
    });//MouseListener
    This gives me the class X Y value, border, maxsize, etc.... when a node is double clicked.
    Does anyone know of a better way?

    Don't use MouseListener.
    Instead, make yourself a TreeSelectionListener as follows:
    public class WhererverYourTreeIs implements TreeSelectionListener
         public void valueChanged(TreeSelectionEvent e)
             TreePath path = e.getPath();
             System.out.println(path.getLastPathComponent());
         public void initStuff()
                 tree.addTreeSelectionLIstener(this);
    }

  • Dynamically changing the color of nodes in a JTree

    I have created a JTree and want to dynamically change the color of some of the TreeNodes as my program runs. The JTree is displayed in a JPanel. There is an algorithm built into which identifies the nodes whose color I need to change. No user actions is performed (everythign is internal to the program).
    It seems that in the TreeCellRender only kicks in when the tree is first displayed. How do I get it to re-render the tree when the TreeModel changes? It seems that the Listeners are only looking for external user interactions.
    Any help would be greatly appreciated.
    Thanks!

    I think I was a bit too vague in my question. Let me try again...
    I have changed an attribute in a node in a JTree. This attribute is changed after the tree was initially rendered, but while the program is still running. I want to tell the TreeCellRenderer to look again at this node since that attribute that was changed will effect how the node should be renderered. I tried using the nodeChanged() method, but it did not work (the colot of the node did not change). Any advise how I can do this?
    Thanks!

  • Hiding / Filtering nodes in a JTree

    I'm not exactly sure how to temporarily hide or filter nodes from a JTree. My scenario is described below.
    I have a radio button group. If the first radio button is selected, all nodes are displayed. If the second button is selected, certain nodes are hidden.
    Here is my attempt to filter nodes. I get the following excpetion when I try to filter nodes:
    java.lang.NullPointerException: Null child not allowed
    I assume this is coming from the getChild() method. I don't know what else to return besides null if I'm trying to filter the node out.
    Can anyone provide some help or insight?
    Thanks
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class MyTreeModel extends DefaultTreeModel
        * Constructor.
        * @param rootNode The root node.
       public MyTreeModel( DefaultMutableTreeNode rootNode )
          super( rootNode );
        * Gets the child node.
        * @param parent The parent node.
        * @param index The index this child node resides in.
        * @return The child node.
       public Object getChild( Object parent, int index )
          Object child = super.getChild( parent, index );
          if ( RadioBtn.hideNodes() )
             DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) child;
             MyNode eNode = ( MyNode ) dmtn.getUserObject();
             if ( !eNode.hasPermission() )
                child = null;    // "hide" the node
          return child;
        * Gets the index of a child.
        * @param parent The parent node.
        * @param child The child node.
        * @return The index of the child node.
        public int getIndexOfChild( Object parent, Object child )
           int index = super.getIndexOfChild( parent, child );
           if ( RadioBtn.hideNodes() )
              DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) parent;
              MyNode eNode = ( MyNode ) dmtn.getUserObject();
              if ( !eNode.hasPermission() )
                 index = -1;
           return index;
        * Returns the number of children attached to the parent node.
        * @param parent The parent node.
        * @return The number of children of the parent node.
       public int getChildCount( Object parent )
          int numChildren = super.getChildCount( parent );
          if ( RadioBtn.hideNodes() )
             int counter = 0;
             DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) parent;
             // Loop through children and keep a count of all children nodes that should stay
             for ( int x = 0; x < numChildren; x++ )
                DefaultMutableTreeNode childDmtn = ( DefaultMutableTreeNode ) dmtn.getChildAt( x );
                MyNode eNode = ( MyNode ) childDmtn.getUserObject();
                if ( eNode.hasPermission() )
                   counter++;
             numChildren = counter;
          System.out.println( "Number of children in " + ( DefaultMutableTreeNode ) parent + ": " + numChildren );
          return numChildren;
        * Used from radio buttons to toggle hidden folders on and off.
       public void triggerMe()
          reload();

    Here it is optimized, for anyone who may need the code down the road.
       public Object getChild( Object parent, int index )
          Object child = super.getChild( parent, index );
          if ( RadioBtn.isHidden() ) // If we should remove the 'special' nodes
             DefaultMutableTreeNode dParent = ( DefaultMutableTreeNode ) parent;
             int count = 0;
             // Loop through children
             for ( int x = 0; x < dParent.getChildCount(); x++ )
                DefaultMutableTreeNode dChild = ( DefaultMutableTreeNode ) dParent.getChildAt( x );
                MyNode eNode = ( MyNode ) dChild.getUserObject();
                if ( eNode.hasPermission() )
                   // If it is the "xth" visible node, break the loop and set this object as the Child node
                   if ( count == index )
                      child = dChild;
                      break;
                   count++;
          return child;
       }

  • Can I  Have JTable As Leaf Node Of A JTree?

    Hello there,
    I want to show jtable on a click of a node of a tree. I have seen Treetable utlility on SUN's site. But it not quite what i want.
    Does any one have any idea how to show JTable as a leaf node of a JTree.
    E.g There is a tree called Components. viz.
    Component
    |Node1
    |Node2
    On click of Node1 i should see Table1 and on click of Node2 i should see Table2.
    If anyone has any idea, can you explain how to do it Or some site name where help on this problem is available?
    Please mail back.
    Regards,
    Amit

    I used insertNodeInto() to inser a new node into the tree, and it can be displayed. But when I used addTreeSelectionListener() to click on the newly added node, it cann not reaspond the click. Following is my original addTreeSelectionListener(). You see, if you click a node of FARInfo, then it will open a form, and after user filled in and submit it, a new node will be added into the Jtree. If you click a node of FilledInfo, then the user should view the content of this new node. But now, it seems that the sencond click cannot work. Thanks for your help.
    tree.addTreeSelectionListener( new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent e4)
    DefaultMutableTreeNode node = ( DefaultMutableTreeNode )
    (tree.getLastSelectedPathComponent ());
    Object nodeInfo = node.getUserObject();
    if (node.isLeaf())
    if ( nodeInfo instanceof FARInfo )
    FARInfo category = (FARInfo) nodeInfo;
    displayURL ( category.categoryURL );
    displayForm ( category.farFormName );
    if ( DEBUG )
    System.out.print ( category.categoryURL + ":\n" );
    else if ( nodeInfo instanceof FilledInfo )
    FilledInfo category2 = ( FilledInfo ) nodeInfo;
    displayFilledForm ( category2.num );
    }else
    return;

  • How to not display nodes in a tree if Oracle roles are NOT used?

    How to not display nodes in a tree if Oracle roles are NOT used?
    We don't use Oracle DB roles to grant users access to Forms from the menu. We use a template and role system of our own. Basically a few tables with templates and roles.
    We want to convert our normal Forms menu to a tree menu and one of our key requirements is that when the tree is populated ONLY nodes with programs (i.e. forms) he has been granted to execute is shown.
    Since we don't use Oracle Roles how to do this in a tree?
    I created a function to show/hide LEAF nodes, BUT problem is that there are sub-menu nodes showing even if the leaf-nodes under it has not being displayed. My function has suppressed it.
    My tree query is like this:
    SELECT
         t.status, LEVEL, t.label, t.icon, t.node VALUE
    FROM
         tma_tree_menu t
    WHERE
    tma_authenticate_sys_chk_role(USER, t.node) = 1
    CONNECT BY
         PRIOR t.node = t.master
    START WITH
         t.MASTER IS NULL
    ORDER SIBLINGS BY
    t.position
    The tma_authenticate_sys_chk_role will return 1 only if the user has access to the form under that node.
    I tried the FTree functions in Forms but even that has nothing.
    Any help would be greatly appreciated.
    Edited by: Channa on Mar 17, 2010 6:49 AM

    Would you share the source code? I guess what I need is how exactly you retreive the user credentials from the DB table and set that boolean variable.
    and then how to condition it in UIX?

  • How do i expand all the nodes in a jtree

    Hi,
    I am working on a project where i need to expand all the nodes of a jtree i have tried a few different ways but it never seems to expand all the nodes..
    I would be very greatful if someone could point me in the right direction
    cheers
    Mary

    you could use the following method that expands nodes recursively
    expandNode( myTree, myRootNode, new TreePath( myRootNode ) );
    public static void expandNode( JTree tree, TreeNode node, TreePath path ) {
        tree.expandPath( path );
        int i = node.getChildCount( );
        for ( int j = 0; j< i; j++ ) {
            TreeNode child = node.getChildAt( j );
            expandNode( tree, child , path.pathByAddingChild( child ) );
    }

  • Sorting the nodes of a JTree

    Can anyone tell me how to go about sorting the nodes in a JTree?

    The best way to do it is thru the treemodel. Either adjust the order in a DefaultTreeModel, or create your own TreeModel.

  • How do I get a dotted line to connect nodes in a JTree?

    I am trying to recreate a Windows Explorer application, does anyone know how they get the dotted lines to connect the nodes in the JTree????

    JTree uses a specific line style to represent the edges between nodes. The default is no edges, but we can set JTree�s lineStyle client property so that each parent node appears connected to each of its child nodes by an angled line:
    myJTree.putClientProperty("JTree.lineStyle", "Angled");
    We can also set this property such that each tree cell is separated by a horizontal line:
    myJTree.putClientProperty("JTree.lineStyle", "Horizontal");
    To disable the line style:
    myJTree.putClientProperty("JTree.lineStyle", "None");
    As with any Swing component, we can also change the UI resource defaults used for all instances of the JTree class. For instance, to change the color of the lines used for rendering the edges between nodes as described above, we can modify the entry in the UI defaults table for this resource as follows:
    UIManager.put("Tree.hash", new ColorUIResource(Color.lightGray))
    Hope this serves your purpose.
    Regards,
    Sachin Shanbhag

  • How can I get a count of ALL nodes in a JTree?

    Not sure if I am missing something here or what. Is there an easy way to determine the total number of nodes in a JTree? I thought there would be a method to return this, but I'm not seeing it in JTree or DefaultTreeModel. Do I have to start at the root and recursively get child counts? Yuck!
    Jamie

    You are absolutely right! Create a recursive method and count all your children from the root.
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

Maybe you are looking for