Unselect node in tree/jtree

http://forum.java.sun.com/thread.jspa?threadID=5137059&tstart=0

Hi Thanks for your replay.
you wrote:
"As I have observed the TreeSelectionListener will respond when first time the node is clicked and then mouse listener.Later on any number of clicks on same node,mouse listener will listen."
my questions:
when we implement both mouse listener and TreeSelectionListener
they will both respond when we select the node.
my mission will be here to stopped mouse to respond .
first question:
how can i do it????
when the node already select and i clicked it again than only mouse will respond so this is not a problem because only the mouse will respond.
i hope i make it clear.
TIA

Similar Messages

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

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

  • How can I view the newly added node in a JTree

    Hi! I have a problem with my project. I set up a JTree. At first it has a node that contains FARInfo object. When I click this node, the other program in the package will pop up a form to let user input and submit, then it will add a new node into the other node. The new node will contain FilledInfo object. But I cannot view this newly added node. The source code related with the 2 different object is as following:
    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;
    My question is: how to deal with the nodes containing 2 different objects: FARInfo and FilledInfo? FilledInfo is created by the other program in the package. Thanks for your help!

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

  • 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

  • Problems generating nodes in a JTree

    Hi Folks,
    I'm having difficulty in generating a JTree. The code follows. Basically, my application creates objects in a hierarchical fashion. The application creates objects of the classes Source, Requirement, DesignElement, ImplementationElement and TestSpecification.
    Objects of each class have a parent relationship with the next, i.e., Source acts as parent to Requirement, Requirement to DesignElement etc. The Source, Requirement etc. classes each have a method for adding a child object, where the object is added to a Vector. Each parent may have more than one child.
    The method generateTree() gets called first, which in turn calls addNodes(). addNodes() is supposed to add parent nodes and their children recursively. An example would be as follows;
    root
    |
    --- S1 - Source 1
    |
    --- S2 - Source 2
    | |
    | --- R1 - Requirement 1
    | |
    | --- D1 - Design 1
    |
    --- S3 - Source 3
    etc.
    Providing that I only add Source and Requirement objects, the tree is generated correctly. If I try to add a Design Element or below,
    either the node doesn't show, or I loss other nodes.
    I've really been tearing my hair out over this and would really appreciate any advice over where I'm going wrong!
    Martin :-(
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.Vector;
    * Provides services for regenerating the tree when artifacts are added or removed.
    public class TreeServices {
      private static Vector sourceList, childArtifacts;
      private static JTree tree;
      private static DefaultMutableTreeNode newNode;
       * Cycles through each source artifact, adding them as a node to the tree and calling
       * addNodes() to add subsequent generations of children to the tree.
      public static JTree generateTree(JTree tree, ArtifactDatabase database) {
        sourceList = database.getSourceList();
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Project");
        tree = new JTree(top);
        DefaultMutableTreeNode node = null;
        for (int i = 0; i < sourceList.size(); i++) {
          node = new DefaultMutableTreeNode(sourceList.elementAt(i));
          top.add(node);
          addNodes((TraceabilityArtifact)sourceList.elementAt(i), node);
        return tree;
       * Adds children nodes to the tree recursively.
      private static void addNodes(TraceabilityArtifact art, DefaultMutableTreeNode node) {
        childArtifacts = art.getChildArtifacts();
        if (!childArtifacts.isEmpty()) {
          for (int i = 0; i < childArtifacts.size(); i++) {
            newNode = new DefaultMutableTreeNode(childArtifacts.elementAt(i));
            node.add(newNode);
            if (!(((TraceabilityArtifact)childArtifacts.elementAt(i)).getChildArtifacts()).isEmpty()) {
              addNodes((TraceabilityArtifact)childArtifacts.elementAt(i), newNode);
    }

    U need to call reload() method on ur TreeModel.
    ((DefaultTreeModel)tree.getModel()).reload()
    i u wanna reload complete tree
    or
    ((DefaultTreeModel)tree.getModel()).reload(TreeNode node) if u wanna reload a particular treenode
    hope this works
    Enjoy !!
    Raj

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

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

  • 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

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

  • 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

  • Duplicate nodes in a JTree

    Hello,
    How i can i find duplicate nodes in a JTree. And give out a message that the node already exists.
    Thanks.
    Reg,
    suri

    The first you have to defind what is dublicating, because the node in the tree is a node itself (e.g. with label node name and icon) and node can have user object that can contains some defind logics and attributes like ID. And then if you just want to not alow to have node with the same name you will check node label. But if you want avoid adding the node with the same user object you have to implement some comparation mechanism on the node or user object lavel.
    Hope will help.

Maybe you are looking for

  • Getting to LOM ?

    Hi, I am trying to access a T2000 via a serial port. There is no monitor, keyboard etc. As far as I know, Solaris has been removed from the box. When the machine starts up I get the following output. It asks for a username and password. I don't know

  • Restricted user cannot run applescript application

    I have written an applescript application (locked) for students using iMacs on our win2000 network to dismount pc shares. The applications accessed by the students are restricted via parental controls. When I search and select the application (logout

  • Problem in AUC Settelement

    Dear all, i have a problem at AUC settlement , i am using T-code AIBU, system is giving error - "transaction type 345 not possible -(posting  to affiliated company). i am settling asset in same company code, there is no chance to post other company,

  • Lightroom 5 changes crop history

    so I keep having a problem where I crop inlightroom, get a photo all set, move on to the next one and then come back and it automatically reverts back to the crop before the final, so I have to go back one stop in the history to where I actually left

  • Fault handling using BPEL

    Good, I'm working on a research project and I have been assigned the task of processing errors in SOAP BPEL. I've been searching on Internet and the most commonly methodology used is soap-fault with throwing and catching exceptions in BPEL process. I