Restricting Jtree node from collapsing.

Hi all,
Is there any way by which i can restrict a Jtree node from collapsing?
please help,
thx,
Soni.

hi
i got it,
here is the solution
tree.addTreeWillExpandListener(new TreeWillExpandListener() {
public void treeWillExpand(TreeExpansionEvent e)throws ExpandVetoException {
public void treeWillCollapse(TreeExpansionEvent e)throws ExpandVetoException {
TreePath p = e.getPath();
DefaultMutableTreeNode n =
(DefaultMutableTreeNode)p.getLastPathComponent();
if (n == root) {
throw new ExpandVetoException(e);
-Soni

Similar Messages

  • Adding JTree nodes from worker threads

    I'm trying to add a large number of nodes (> 1700) to a JTree, and I'm looking for a way to do this while allowing the user to continue working in the meantime.
    The nodes are retrieved from a database, which may be geographically distant and therefore possibly slow to access. I would like to have the process of processing the result-set and creating the Nodes run separately.
    I have considered processing the result-set in a separate Thread and creating the Nodes before then returning to the EDT to add them to the tree. This would cause the GUI to pause when adding the Nodes to the tree, but does at least separate the DB access out of the EDT.
    I would prefer to update the tree node by node as the result-set is processed, but I'm not sure whether this would incur too much overhead.
    I would appreciate any advice.

    I'm not sure overhead is the problemimport java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.Random;
    public class Test extends JFrame implements Runnable {
      JTree jt = new JTree();
      DefaultTreeModel dtm = (DefaultTreeModel)jt.getModel();
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        new Thread(this).start();
        setSize(500, 500);
        setVisible(true);
      public void run() {
        Random r = new Random();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode)dtm.getRoot();
        for (int i=0; i<1700; i++) {
          DefaultMutableTreeNode item = (DefaultMutableTreeNode)root.getChildAt(r.nextInt(root.getChildCount()));
          while (r.nextInt(5)>0 && item.getChildCount()>0) {
            item = (DefaultMutableTreeNode)item.getChildAt(r.nextInt(item.getChildCount()));
          item.add(new DefaultMutableTreeNode("Node-"+i));
          dtm.nodeStructureChanged(item);
          try { Thread.sleep(500); } catch (Exception e) {}
      public static void main(String[] args) { new Test(); }
    }

  • Remove white space nodes from jtree

    I am trying to create jtree using XML DOM.
    But I m not able to remove/ignore the white space elements from DOM.
    I am getting output something like this
    for example
    Server
    Text
    node1
    Text
    I want something like this.
    Server
    node1
    I tried all option for removeing the white space
    Here I am posting the source
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import java.io.File;
    import java.io.IOException;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    // Basic GUI components
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    // GUI components for right-hand side
    import javax.swing.JSplitPane;
    import javax.swing.JEditorPane;
    // GUI support classes
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    // For creating borders
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.CompoundBorder;
    // For creating a TreeModel
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.*;
    public class DomEcho02 extends JPanel
    // Global value so it can be ref'd by the tree-adapter
    static Document document;
    static final int windowHeight = 460;
    static final int leftWidth = 300;
    static final int rightWidth = 340;
    static final int windowWidth = leftWidth + rightWidth;
    public DomEcho02()
    // Make a nice border
    EmptyBorder eb = new EmptyBorder(5,5,5,5);
    BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
    CompoundBorder cb = new CompoundBorder(eb,bb);
    this.setBorder(new CompoundBorder(cb,eb));
    // Set up the tree
    JTree tree = new JTree(new DomToTreeModelAdapter());
    // Iterate over the tree and make nodes visible
    // (Otherwise, the tree shows up fully collapsed)
    //TreePath nodePath = ???;
    // tree.expandPath(nodePath);
    // Build left-side view
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(
    new Dimension( leftWidth, windowHeight ));
    // Build right-side view
    JEditorPane htmlPane = new JEditorPane("text/html","");
    htmlPane.setEditable(false);
    JScrollPane htmlView = new JScrollPane(htmlPane);
    htmlView.setPreferredSize(
    new Dimension( rightWidth, windowHeight ));
    // Build split-pane view
    JSplitPane splitPane =
    new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
    treeView,
    htmlView );
    splitPane.setContinuousLayout( true );
    splitPane.setDividerLocation( leftWidth );
    splitPane.setPreferredSize(
    new Dimension( windowWidth + 10, windowHeight+10 ));
    // Add GUI components
    this.setLayout(new BorderLayout());
    this.add("Center", splitPane );
    } // constructor
    public static void main(String argv[])
    if (argv.length != 1) {
    System.err.println("Usage: java DomEcho filename");
    System.exit(1);
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    //factory.setValidating(true);
    //factory.setNamespaceAware(true);
    try {
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.parse( new File(argv[0]) );
    makeFrame();
    } catch (SAXException sxe) {
    // Error generated during parsing)
    Exception x = sxe;
    if (sxe.getException() != null)
    x = sxe.getException();
    x.printStackTrace();
    } catch (ParserConfigurationException pce) {
    // Parser with specified options can't be built
    pce.printStackTrace();
    } catch (IOException ioe) {
    // I/O error
    ioe.printStackTrace();
    } // main
    public static void makeFrame() {
    // Set up a GUI framework
    JFrame frame = new JFrame("DOM Echo");
    frame.addWindowListener(
    new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    // Set up the tree, the views, and display it all
    final DomEcho02 echoPanel =
    new DomEcho02();
    frame.getContentPane().add("Center", echoPanel );
    frame.pack();
    Dimension screenSize =
    Toolkit.getDefaultToolkit().getScreenSize();
    int w = windowWidth + 10;
    int h = windowHeight + 10;
    frame.setLocation(screenSize.width/3 - w/2,
    screenSize.height/2 - h/2);
    frame.setSize(w, h);
    frame.setVisible(true);
    } // makeFrame
    // An array of names for DOM node-types
    // (Array indexes = nodeType() values.)
    static final String[] typeName = {
    "none",
    "Element",
    "Attr",
    "Text",
    "CDATA",
    "EntityRef",
    "Entity",
    "ProcInstr",
    "Comment",
    "Document",
    "DocType",
    "DocFragment",
    "Notation",
    // This class wraps a DOM node and returns the text we want to
    // display in the tree. It also returns children, index values,
    // and child counts.
    public class AdapterNode
    org.w3c.dom.Node domNode;
    // Construct an Adapter node from a DOM node
    public AdapterNode(org.w3c.dom.Node node) {
    domNode = node;
    // Return a string that identifies this node in the tree
    // *** Refer to table at top of org.w3c.dom.Node ***
    public String toString() {
    String s = typeName[domNode.getNodeType()];
    String nodeName = domNode.getNodeName();
    if (! nodeName.startsWith("#")) {
    s += ": " + nodeName;
    if (domNode.getNodeValue() != null) {
    if (s.startsWith("ProcInstr"))
    s += ", ";
    else
    s += ": ";
    // Trim the value to get rid of NL's at the front
    String t = domNode.getNodeValue().trim();
    int x = t.indexOf("\n");
    if (x >= 0) t = t.substring(0, x);
    s += t;
    return s;
    * Return children, index, and count values
    public int index(AdapterNode child) {
    //System.err.println("Looking for index of " + child);
    int count = childCount();
    for (int i=0; i<count; i++) {
    AdapterNode n = this.child(i);
    if (child.domNode == n.domNode) return i;
    return -1; // Should never get here.
    public AdapterNode child(int searchIndex) {
    //Note: JTree index is zero-based.
    org.w3c.dom.Node node =
    domNode.getChildNodes().item(searchIndex);
    return new AdapterNode(node);
    public int childCount() {
    return domNode.getChildNodes().getLength();
    // This adapter converts the current Document (a DOM) into
    // a JTree model.
    public class DomToTreeModelAdapter
    implements javax.swing.tree.TreeModel
    // Basic TreeModel operations
    public Object getRoot() {
    //System.err.println("Returning root: " +document);
    return new AdapterNode(document);
    public boolean isLeaf(Object aNode) {
    // Determines whether the icon shows up to the left.
    // Return true for any node with no children
    AdapterNode node = (AdapterNode) aNode;
    if (node.childCount() > 0) return false;
    return true;
    public int getChildCount(Object parent) {
    AdapterNode node = (AdapterNode) parent;
    return node.childCount();
    public Object getChild(Object parent, int index) {
    AdapterNode node = (AdapterNode) parent;
    return node.child(index);
    public int getIndexOfChild(Object parent, Object child) {
    AdapterNode node = (AdapterNode) parent;
    return node.index((AdapterNode) child);
    public void valueForPathChanged(TreePath path, Object newValue) {
    // Null. We won't be making changes in the GUI
    // If we did, we would ensure the new value was really new,
    // adjust the model, and then fire a TreeNodesChanged event.
    * Use these methods to add and remove event listeners.
    * (Needed to satisfy TreeModel interface, but not used.)
    private Vector listenerList = new Vector();
    public void addTreeModelListener(TreeModelListener listener) {
    if ( listener != null
    && ! listenerList.contains( listener ) ) {
    listenerList.addElement( listener );
    public void removeTreeModelListener(TreeModelListener listener) {
    if ( listener != null ) {
    listenerList.removeElement( listener );
    // Note: Since XML works with 1.1, this example uses Vector.
    // If coding for 1.2 or later, though, I'd use this instead:
    // private List listenerList = new LinkedList();
    // The operations on the List are then add(), remove() and
    // iteration, via:
    // Iterator it = listenerList.iterator();
    // while ( it.hasNext() ) {
    // TreeModelListener listener = (TreeModelListener) it.next();
    * Invoke these methods to inform listeners of changes.
    * (Not needed for this example.)
    * Methods taken from TreeModelSupport class described at
    * http://java.sun.com/products/jfc/tsc/articles/jtree/index.html
    * That architecture (produced by Tom Santos and Steve Wilson)
    * is more elegant. I just hacked 'em in here so they are
    * immediately at hand.
    public void fireTreeNodesChanged( TreeModelEvent e ) {
    Enumeration listeners = listenerList.elements();
    while ( listeners.hasMoreElements() ) {
    TreeModelListener listener =
    (TreeModelListener) listeners.nextElement();
    listener.treeNodesChanged( e );
    public void fireTreeNodesInserted( TreeModelEvent e ) {
    Enumeration listeners = listenerList.elements();
    while ( listeners.hasMoreElements() ) {
    TreeModelListener listener =
    (TreeModelListener) listeners.nextElement();
    listener.treeNodesInserted( e );
    public void fireTreeNodesRemoved( TreeModelEvent e ) {
    Enumeration listeners = listenerList.elements();
    while ( listeners.hasMoreElements() ) {
    TreeModelListener listener =
    (TreeModelListener) listeners.nextElement();
    listener.treeNodesRemoved( e );
    public void fireTreeStructureChanged( TreeModelEvent e ) {
    Enumeration listeners = listenerList.elements();
    while ( listeners.hasMoreElements() ) {
    TreeModelListener listener =
    (TreeModelListener) listeners.nextElement();
    listener.treeStructureChanged( e );
    }

    DocumentBuilderFactory can be configured to ignore white space.
    http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilderFactory.html#setIgnoringElementContentWhitespace(boolean)

  • JTree refresh without collapsing my nodes

    Hello,
    I have a JTree using a custom TreeModel. I've also extended the TreeNode.
    What is the most elegant method to refresh the tree or only a node without
    collapsing the currently expanded nodes?
    Please note that there are multiple types of TreeNodes each representing
    a different object to display in the tree and contains an object that represents its
    value. Also the node has a method createChildren() to determine and create
    the child TreeNodes. Children are loaded from a business delegate. I need the
    tree to re-query the model (maybe for only one node) about the data and redisplay
    the changes without affecting the collapsed/expanded state of the nodes that
    are not changed (not supposed to refresh).
    My model actually asks the node for data like getChildsCount(), isLeaf() etc, etc.
    I'd like to say:
    myCustomNodeInstance.refresh();
    or
    myCustomTreeModelInstance.refresh(myCustomNodeInstance);
    and all nodes that are not children of myCustomNodeInstance to preserve
    their state.
    Thanx

    Did you try to call repaint() method on JTree ?

  • Is it possible to restrict the user from creating a sibling and allow him to ONLY create child nodes in DRM?

    When in a hierarchy, a user right clicks on a node to crate a new node, he has two options
    -Child
    -Sibling
    Is it possible to restrict the user from creating a sibling and allow him to ONLY create child nodes?
    Business cases:
    1. different level nodes need to have different prefixes.
    - Thus, the default prefix property definition uses the level number to assign a prefix
    - Also, a validation, to ensure the correct prefix, uses the level number
    But if the user can create a child and a sibling then the default prefix will only be right for a single case and not both.
    Thanks

    If the images are exactly the same size then make sure the layer with the mask
    is the active layer and in the other documents go to Select>Load Selection and choose
    your document with the layer mask under Source document and under channel choose the layer mask.
    After the selection loads press the layer mask icon at the bottom of the layers panel.
    MTSTUNER

  • How to Remove a Node from JTree?

    I want to remove a node from a JTree but the node may or maynot be visible.
    My method takes a String which is the name of the node.
    The nodes im using are DefaultMutableTreeNode
    This is my code so far but it doesnt work.
    public void removePerson(String pName)
              TreePath node = tree.getNextMatch(pName,0,Position.Bias.Forward);
              tree.expandPath(node);
              tree.removeSelectionPath(node);
    }Any Suggestions or ways which i could achive this?
    Thank you,

    I don't think removeSelectionPath is what you want to use.
    These should help:
    [http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)|http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)]
    [http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml|http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml]

  • Jtree node refuses to collapse upon clicking handle; makeVisible() was used

    Hello,
    While creating a new node and inserting as a leaf in the JTree, I use tree.makeVisible(newTreePath) to expand the new node and make visible. (Using expandPath() will not expand if a leaf was added).
    However now the jtree node refuses to collapse upon clicking the node handle.
    How do I get it to not insist on staying open - be able to collapse manually?
    thanks,
    Anil

    This is the JNI forum. I don't believe your post fits.
    then
    can I correctly assume that any class that
    "implements Cloneable" will handle making either a
    "shallow" or "deep" ... or even "semi-shallow" clone,
    respective to the class context .. right?
    It probably does something. The implementor might not have implemented anything though. And you have no idea what they implemented.
    No idea about your other question.
    You might want to think carefully about why you are cloning though.

  • Deleting Nodes from XML Tree (JTree)

    I have created a XML Tree(extended from JTree) using XNodes ( extended from DefaultMutableTreeNode)
    After some insertions, i need to delete certain nodes from the XML Tree.. but after deletion, XNode will be null.
    subroutine is as follows...
    appreciates any advice
    Thanx
    private XNode RemoveExtraNode( XNode xNode ){
    int child;
    String nodeType;
    XNode childNode=null;
    if ( (child=xNode.getChildCount() ) > 0){
    for(int i=0;i<child;i++){
    childNode=(XNode)xNode.getChildAt(i);          
         nodeType = childNode.getType();
         if(nodeType.equals("DTD") )
         childNode.removeFromParent();
    }//end for (int i=1;i<child;i++)
    }//endif((child=xNode.getChildCount())!=0)
    return xNode;     
    }//RemoveExtraNode

    Hi IKEDA
    Thanx for the reply.
    I have tried xNode.remove(childNode) b4 and it still return a null JTree.
    Anyway fyi i discover i can delete last child of xNode and return the correct java tree. therefore to delete a node of my choice i simply insert its next sibling nodes in its place and delete that particular node when it becomes the last child.

  • How can I remove child node from JTree???

    Hi,
    I would like to remove all the child node of my jtree. For instance I would like to remove the c, d, and e nodes. It's possible to remove all the child node or to remove by her name ("c", "d", and "e"). If yes what is the method that it permit to do.
    A-----
    |
    b-------c
    |
    |--------d
    |
    ---------e
    I use the model : DefaultMutableTreeNode
    Thanks

    There are a couple of ways it can be done. If your tree uses DefaultTreeModel as its TreeModel, you can use removeNodeFromParent(). This will remove the node from its parent and effectively remove its children, too. All nodes removed will be garbage-collected if there are no other references to them.
    If your tree model is not the default tree model, but still uses MutableTreeNode, you can use either remove() or removeFromParent() on the node itself, depending on whether you want to remove the node itself or one of its children.
    On the other hand, your tree may use a model that simply "mirrors" another data structure, in which case you would have to remove the node from the other data structure and have it reflected in the model.

  • How to remove all nodes (except root node)from a Jtree?

    How to remove all nodes (except the root node)from a Jtree?

    Either:
    - remove all children of root.
    - save the root node, throws away the tree model, build a new TreeModel with the saved root, set the new TreeModel in the JTree.
    - implement your own TreeModel, which would support an emptyExceptRoot() method.
    IMHO, using the DefautlTreeModel and DefaultMutableTreeNode does lead to all sorts of small problems when the app evolves, and implementing your own TreeNode and TreeModel is not that hard and much more efficient.

  • How to retrieve the nodes from the Database on JTree and many more

    I am facing a problem with JTree. I want to retrieve all the nodes from the MS-Access database on the Frame(i.e. Frame will display the JTree), then I also want to perform function like Edit, insert , delete and Drag and Drop opeartion on the JTree and the database should also updated accordingly.
    So, if you have any idea or if you have some code to look for then please send it to me.

    I am facing a problem with JTree. I want to retrieve all the nodes from the MS-Access database on the Frame(i.e. Frame will display the JTree), then I also want to perform function like Edit, insert , delete and Drag and Drop opeartion on the JTree and the database should also updated accordingly
    pls give me code

  • How to remove a node from  a Jtree?

    I tried giving this to move a node from one parent node to other parent node.
    IconNodeClass userObject = (IconNodeClass)tr.getTransferData(TransferableDataItem.Image_Tree_Node_Flavor);
    IconNodeClass node = (IconNodeClass)path.getLastPathComponent();
    IconNodeClass newNode = new IconNodeClass(userObject);
    DefaultTreeModel model = (DefaultTreeModel)getModel();
    IconNodeClass oldParentNode = (IconNodeClass)userObject.getParent();
    Object oldParent = oldParentNode.getUserObject();
    Object newParent = node.getUserObject();
    if(oldParent.equals(newParent)) {
    model.insertNodeInto(newNode, node, 0);
    if(oldParentNode != null) {
    oldParentNode.remove(newNode);
    model.reload(oldParentNode);
    }

    what happened next ?????

  • Dynamiclly remove node from JTree

    hi all,
    I want to remove nodes from a tree dynamically. I used "treeModel.removeNodeFromParent(node);". The node was removed from that treeModel, but the tree never updated. I tried to use tree.repaint() method. It doesn't work. Any suggestion?
    thanks a lot in advance.

    try with TreeModel.reload(); This will surely work

  • How to hide node handles (legs) from JTree nodes?

    Hello,
    Does anyone has an idea on how to not display JTree node handles (legs)?
    Thank you,
    Mindaugas

    You can do it with Java/Metal look and feel by doing this:
    JTree tree = new JTree(...);
    tree.setClientProperty("JTree.lineStyle", "None");
    For any other L&F, you will have to look at the UI code.
    Mitch Goldstein
    Author, Hardcore JFC

  • JTree Node Color, to distinguish between different activities

    Hi,
    Situation:          Dynamic JTree (Tree is constructed from as a result of Database). User has the option to either Enable / Disable node and can repeat the activities but restricted only one activity per node, the node is to be highlighted; to restrict the user from further activities.
    Problem:          Am a newbie to swing, after searching the forum for the same, i found few good solutions which are specific to color change of specific selected node, in a temporary context.
         But we need the node color change within a same level; to distinguish either the node is either enabled / disabled.
    Your help is appreciated,

    durino13 wrote:
    1. Is the approach above a good approach, how to load children 'lazilly'?Sounds pretty reasonable to me.
    2. I also use custom renderer to display different icons for every "tree" level. When I initially expand the 4th level, everything works fine !!! Then I collapse the 4th level and expand it again and here my problem starts: my 4th level icon is set to 'root level icon' instead of '4th level' icon. This does not happen, if computerNode.removeAllChildren(); method is removed from listening above
    Any idea, what am i doing wrong?Ummmm... Load the model the first time (only) the node is expanded... Putz!
    And I suggest you listen deeply to Mr Jacobs... He really does know what he's talking about ;-)
    ... and not this time, but in future: Swing questions are best asked in [THE Swing Forum|http://forums.sun.com/forum.jspa?forumID=57].
    Cheers. Keith.

Maybe you are looking for

  • Want a TN to block to ADD Purchase order Canditions Are as follows:-

    Respective Experts,          I want a TN to block ADD Purchase Order Conditions are as follows:-          When I add Purchase order it goes for approval and the document is saves as Draft Now    1) If there is 6 Purchase orders for a Vendor are pendi

  • Loss of quality on Import from Camera

    Hi Im importing footage from my camera to FCP, they are mini DV tapes, and Im just coming in through the fire wire using capture. When the footage gets in to FCP it looks a bit grainy and darker. Does the quality of my camera have anything to do with

  • Mystery disk images

    Last June I experimented with burning a CD from a disk image. Since then, two disk images have sat in the sidebar of Disk Utility. They can be opened to volumes on the desktop, and the volumes have songs that can be played. Those disk images have no

  • Exception aggregation for calculated key figure

    Is it possible to have exception aggregation for calculated key figure in BW 3.5? As per Note 1151857, it is possible, however this note applies to BI 7.0. As per note 152638, it is possible in older version only simple ckfs like 'CKF = Base key figu

  • Table name containing report job status

    Can anyone tell me what the name of the table is that contains the information that is viewable via the Enterprise Manager concerning the current/failed/finished jobs on the report server. Thanks.