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;
   }

Similar Messages

  • Hiding nodes in a JTree

    Hi,
    Is it possible to hide a particular node in a JTree? (i dont mean collapsing a node) ie to make some node invisible?Plz reply, deadline's coming.
    Thanks in advance,
    -Adhiraj.

    If I need to "hide" a node, I find easier to remove it from a tree.
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • 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 ) );
    }

  • 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);
    }

  • 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/

  • 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!

  • Getting TreePath for all nodes in a JTree

    Hi everybody
    I want to get TreePath for all the nodes in a JTree
    Can anybody help me?

    Hi,
    i tried to used your code.
    there is a problem, it is not taking the entire paths.
    so if you have some children,it takes the paths only for the fathers.
    so i correct it to the following way(it will take the entire paths):
    public void getPathForAllNodes(TreePath path)
                  Object node = path.getLastPathComponent();
                  pathArrayList.add(path);
                  TreeModel model = tree.getModel();
                  if(model.isLeaf(node))
                  return;
                  int num = model.getChildCount(node);
                  for(int i = 0; i < num; i++)
                       //pathArrayList.add(path);
                       getPathForAllNodes(path.pathByAddingChild(model.getChild(node, i)));
             }thanks for your code

  • Can I move nodes in a jTree without the mouse?

    I want to move nodes in a jTree as if I was dragging and dropping but I don�t want to use the mouse. Is this possible and how.

    I want to move nodes in a jTree as if I was dragging
    and dropping but I don�t want to use the mouse. Is
    this possible and how.sure it's possible through the power of Java(tm)

  • Events of Nodes in a JTree

    Okay, perhaps I am sidetracked today by all the sad craziness occuring in New York and DC, or perhaps I just don't have a grasp on JTrees yet...but...
    I have implemented a TreeCellRender to create panels with buttons and other information to be the nodes of a JTree I created. Everything shows up beautifully, however, I want the buttons on this panel to depress and perfom actions (work like normal) when the user clicks/selects such a button in the tree structure. I can't figure out how to properly set up event handlers to get from the tree to the tree node to the "bean" I'm using as a node. If anyone has any helpful hints, I'd appreciate it!
    Thanks in advance!

    add actionlistener to the JTree, and then get the object by getLastPathComponent, and compare it if its the button and do the action.

  • Selectively editing nodes in a JTree

    I need to make certain nodes in a JTree editable, without making every node in the tree editable. How can I accomplish this?

    Is there some kind of method in a JTree or a DefaultMutableTreeNode that I can call to select the node's text and be able to change it?Hmm. And you did read the API for JTree looking for such methods before you posted here, didn't you?
    So tell us which methods you found to be likely candidates.
    db

  • Highlighting nodes in a JTree

    Hi,
    I'd like to know how I can produce the efect of highlighting nodes in a JTree when the mouse moves over the JTree.
    Thanks

    You say to get the mouseevent coordinates with a mouse
    listener, but which component should be the caller of
    the methos addMouseListener?
    If I choose the jtree, I can't get the 'mouseevent
    coordinates' each time the mouse moves over a node,
    because the methods mouseEntered and mouseExited are
    invoked just once (when the mouse enter inside the
    jtree's area (mouseEntered), and when the mouse gets
    out the jtree's area(mouseExited)), so I can't change
    the boolean field to true for nodes which have the
    mouse over.just use mouseMoved of the MouseMotionListener.
    however, i have my doubts that you will have a lot of fun with the suggested method (correct though it is).
    at least make sure you only call the repaint method if the mouse moved into a new node. you might want to try the the nodeChanged method, that way you don't repaint the whole tree every time.
    thomas

Maybe you are looking for

  • Duplicated events on iCal, and even more on iPod calendar

    I am using the latest version of Mac OS X Lion and an iPod Touch 2G with the latest compatible iOS update (4.2.1) I gave iCloud a try, but after syncing with my iPod, I wouldn't be able to create or edit events in my iCloud calendars (which were prev

  • Itunes freezes in windows vista

    i have a 32 bit os which i've read is not a problem. can anyone help me? itunes will maybe allow me to copy maybe one track onto ipod, then will not only freeze but i can't close or anything. plz help.

  • How to handle invalid images in "Image" report item?

    I have a report that displays images in Image item (MIMEType image/jpeg) in the table. Images are stored in the database. Some of the images are, however, not a valid jpeg files (not sure what they are but I saved them as files and they cannot be ope

  • Not running pages after upgrade version in oracle apps 11.5.10.2 CU2

    Hello friends, after upgrading version in oracle apps 11.5.10.2 CU2. i could not run any OAF pages in local jdeveloper. i used these patches. 1) p4573517_11i_GENERIC 2)p4045639_11i_GENERIC . i set all properties correct like dbc file,database connect

  • Export option in KE30 Custom report

    Hi All, We have custom reports in KE30 and when we execute them the output is getting displayed. But for few users they are getting the option to export the data into file in the Menu options (Report -> export) but for few it is not coming. Any idea