Expand jTree

Hi,
I have got question how to expand JTree. I am using netbeans IDE.
I would like to save information about last visited position in tree and when I open this window again to expand it to last visited node(leaf).
I have done someting like that:
String hostName = getHostName();
DefaultMutableTreeNode root = new DefaultMutableTreeNode(hostName)
DefaultTreeModel treeModel = new DefaultTreeModel(root);
JTree jTree1 = new JTree();
jTree1.setModel(treeModel);
//I have create method to create jTree:
public void setTree(TreePath path)
DefaultMutableTreeNode newNode;
//Here I call method to get all root folders. For root it will be all disks.
File[] folderList = getFolders(...)
for(File f: folderList)
newNode = new DefaultMutableTreeNode(f);
root.add(newNode);
Ok. That's how it create jTree. This part of code works correct. I invoke this window with other (main) window. I have got treeNode e.g.
[ TRAVEL, C:\, C:\Program Files ]
I strange because I checked that on second level node has leaf but it doesn't handle and folder icon. I have tried jTree1.repaint but it doesn't work.
How can I expand tree to this node. I have been trying:
--scrollPathToVisible method
When I select a node by mouse clicking then tree refreshes and show handle with folder icon and all leafs. I have selected the same node using setSelectionPath(treePath) but it is not working and trying to expand it but it is not working.
Give me a sign if you need more information.
Peter D.

It only took me 20 seconds to do a search and find this, but since you've waited over five hours, here's one result I found
http://forum.java.sun.com/thread.jsp?forum=31&thread=257313

Similar Messages

  • Enter key not expanding JTree branches in 1.4?

    Hi,
    I have noticed that when pressing enter when a node is selected in a Jtree does not perform an expand/collapse on a branch or a programatic "double click" if it is a leaf. This seems to only apply to JDK 1.4. In 1.3 it does have this behaviour.
    Does this sound right?
    If for whatever reason this feature was removed, what is the workaround? I tried using a KeyListener and that did not seem to work.

    I have found a workaround. The following will allow the tree to expand/collapse branches on pressing "Enter".
    tree.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "toggle");where "tree" is an instance of JTree. (BTW, I disconvered this by making a comparison between the WindowsLookAndFeel class in 1.3 and 1.4.)
    However, I still cannot get it to do the programmatic equivelant of double clicking on a leaf. I am able to get a keylistener to listen for when [Enter] is pressed but I don't know where to go from there.
    Here is my code so far.
    * Created on Sep 9, 2003
    package Andar;
    import java.awt.event.*;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.KeyStroke;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * @author avromf
    public class TreeDemo extends JTree
         private DefaultMutableTreeNode currentNode;
         public static void main(String[] args)
              JFrame frame= new JFrame("Test");
              TreeDemo tree= new TreeDemo();
              frame.getContentPane().add(tree);
              frame.setSize(300,200);
              frame.setVisible(true);
         public TreeDemo()
              super();
              getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              addTreeSelectionListener(new TreeSelectionListener()
                   public void valueChanged(TreeSelectionEvent e)
                        currentNode = (DefaultMutableTreeNode) getLastSelectedPathComponent();
              getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "toggle");
              addKeyListener(new KeyAdapter()
                   public void keyTyped(KeyEvent e)
                        if (currentNode != null && currentNode.isLeaf() && e.getKeyChar() == '\n')
                             System.out.println(currentNode);                    
    }Any suggestions?

  • Creating expanded JTree

    Hii
    I've created a JTree which is working well I did something:
            int i = 0;
            treeNode = new DefaultMutableTreeNode("My Computer");
            File roots[] = File.listRoots();
            for(File f : roots)
                childTree = new DefaultMutableTreeNode(f.getAbsolutePath().toString());
                treeNode.insert(childTree,i++);
            model = new DefaultTreeModel(treeNode,true);
            jTree1.setModel(model);This is returning a default model. Actually I'm having a specific path which'll expand when JTree 'll be made at the first time. could you else please tell me how can I pass that path so that, the JTree will open that path by default!!!
    thanks
    Dev

    This will show the whole tree
    private void showTheTree(){
        int c = tree.getRowCount();
        int i = 0;
        while(i <= c){
            tree.expandRow(i);
            i++;
            c = tree.getRowCount(); // as you expand, you get more
        }

  • Way to expanding jTree

    before i add a new node to a jtree some nodes r expanded. so after i added the new node in the JTree i want to show the nodes that were previously expanded in the jtree. what is the way?
    I am using,
    model : DefaultTreeModel
    tree : JTree
    rootnode : DefaultMutableTreeNode
    Now i am calling the model.reload() method. if the user is selected any node in the tree then i add the new node and call the reload, cause the cast cast exception: can't to cast MyObject to TreeNode. why?

    Thank you very much Steve, I was able to integrate
    your code in my own application. It's working fine.
    I will do more tests with it and let you know about
    it.That's terrific Andre. I am very pleased the code worked and helped you. I hope this solution 'nails' the much wondered about JTree refresh problem once and for all.
    Should you come across any bugs, or if you think of any means of improvement during your testing, I would be very interested to hear from you.
    In any case, good luck with your project, and all the best,
    Steve

  • Expanding JTree nodes to the left.

    I have a JTree with a custom model and cell renderer but now i'd like to flip the entire tree so that the root node ends up in the upper right corner and the child nodes expand to the left (instead of to the right).
    I tought this should be easy enough but now I'm very confused; any help is appriciated!

    Hi,
    as a general guideline - you want to set something - so search for all set....-methods that class has or inherits.
    public void setComponentOrientation(ComponentOrientation o)
    Set the language-sensitive orientation that is to be used to order the elements or text within this component. Language-sensitive LayoutManager and Component subclasses will use this property to determine how to lay out and draw components.
    At construction time, a component's orientation is set to ComponentOrientation.UNKNOWN, indicating that it has not been specified explicitly. The UNKNOWN orientation behaves the same as
    ComponentOrientation.LEFT_TO_RIGHT.
    To set the orientation of a single component, use this method.
    Hope, this helps
    greetings Marsian

  • An Expandable JTree Problem

    Hi, I'm relatively new to creating JTree components, now I have looked at many examples, and this one is nearest (i can see) to how I want my Jtree to look, however it doesn't behave in a way which I would like!
    Firstly, I can set the root node to have as many folders as i want, however they only mirror whats in the first root node, I dont want this - I want to be able to create about 5/6 different roots that will yield different results - I also want after each time you click on a folder, which will ask a question about a patient i.e. "Has the patient a head injury" - click on this then it should come up with "3" more different choices, so altogther want it about 5 deep.
    However, this is what I've got so far - but like I say, its not yielding the results I want, does anyone know how to modify this or can anyone point me in the right direction by starting me off a bit, that would be great!
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class SelectableTree extends JFrame
                                implements TreeSelectionListener {
      public static void main(String[] args) {
        new SelectableTree();
      private JTree tree;
      private JTextField currentSelectionField;
      public SelectableTree() {
        super("Clinical Information Help System");
        WindowUtilities.setNativeLookAndFeel();
        addWindowListener(new ExitListener());
        Container content = getContentPane();
        DefaultMutableTreeNode root =
          new DefaultMutableTreeNode("Begin Clinical Questions");
        DefaultMutableTreeNode child = null;
        DefaultMutableTreeNode parent = null;
        DefaultMutableTreeNode grandChild = null;
        DefaultMutableTreeNode grandParent = null;
        DefaultMutableTreeNode child2 = null;
        DefaultMutableTreeNode parents = null;
        for(int grandParentIndex=1; grandParentIndex < 2; grandParentIndex++) {
          grandParent = new DefaultMutableTreeNode("[Does Patient Have Back Pains?] " + grandParentIndex);
          root.add(grandParent);
          for(int parentIndex =1; parentIndex < 3; parentIndex++) {
            parent = new DefaultMutableTreeNode("[Does the patient also have leg pain?] " + parentIndex +
                                         "." + parentIndex);
            grandParent.add(parent);
            for(int childIndex =1; childIndex < 3; childIndex++) {
             child = new DefaultMutableTreeNode("[are the pains in the lower back?] " + childIndex +
                                         "." + childIndex);
              parent.add(child);
              child2 = new DefaultMutableTreeNode("patient over 60?" + childIndex +
                    "." + childIndex);
              child.add(child2);
            for(int grandChildIndex =1; grandChildIndex < 3; grandChildIndex++) {
               grandChild = new DefaultMutableTreeNode("[Does patient have bladder and/or bowel incontinence?] " + grandChildIndex +
                                            "." + grandChildIndex);
                 child.add(grandChild);
            for(int childIndex = 1; childIndex < 3; childIndex++) {
                child = new DefaultMutableTreeNode("[Has Patient suffered either: appitite/wieght loss/fever?]" + childIndex +
                                             "." + childIndex);
                child = new DefaultMutableTreeNode("[Has pain been 4-6wks leg pain? OR 3-6mths low-back pain?]" + childIndex +
                        "." + childIndex);
                  grandChild.add(child);
        tree = new JTree(root);
        //tree = new JTree(root2);
        tree.addTreeSelectionListener(this);
        content.add(new JScrollPane(tree), BorderLayout.CENTER);
        currentSelectionField = new JTextField("Current Selection: NONE");
        content.add(currentSelectionField, BorderLayout.SOUTH);
        setSize(400, 400);
        setVisible(true);
      public void valueChanged(TreeSelectionEvent event) {
        currentSelectionField.setText
          ("Current Selection: " +
           tree.getLastSelectedPathComponent().toString());
    }

    I'm not really sure what your problem is, for I don't see what you mean by "mirror". If it is you have but one root node, but wanted to have many instead, then you'd simply need to call setRootVisible(false); on the tree.
    As a sidenote, I don't think it's a really good UI for what you're doing, but after all, I haven't got the whole picture.
    Now, what is it you mean by: its not yielding the results I want ?

  • Expand JTree using

    hi there,
    I have a JTree with DefaultMutableTreeNode as nodes each node represent a string.
    I have to ways to watch my data JTable and and JTree both are visible, I need to sync between them.
    sync the JTable to the JTree was easy, but now I don't have a clue how to sync the JTree to the JTable.
    both contain string as data.
    cause my app is kind of a Virtual HD, I display on the JTree and the JTable my files and directories.
    my intuition was to pass the current path to the JTree but I don't know how to create a TreePath to the needed node
    thank you

    Convert your node path to a TreePath and call expandPath.

  • Expand a path in JTree

    Hi all. Please help, I am trying to programmatically expand JTree with JTree.expandPath(path), but it only works one level downwards from the last physically selected node. Is this a bug, or am I doing something wrong?

    If you are using DefaultMutableTreeNode for your nodes, thenTreePath tp = new TreePath(theNode.getPath());gets you a path from the root to theNode. If you want that to be the selection, thentheTree.setSelectionPath(tp);and if you want it to be expanded and viewable thentheTree.expandPath(tp);If you aren't using DefaultMutableTreeNode, you will have to build the TreeNode[] that contains the nodes from the root down to theNode by some kind of loop; the rest of the code still works.

  • Expand a TreePath in a JTree

    hi
    i face a really strange problem at the moment.
    from my main tree, i want to copy the selected TreePath to my tree in a dialog.
    so i pass the TreePath to the dialog and call the following method:
    tree.expandPath(path);in the tree-initialization i set setExpandsSelectedPaths to true, so the path should be expanded.
    nothing happens.
    either no effect if i call directly expandPath().
    does anybody have an idea why this happen like this?
    thx & greetz
    swissManu

    Hi,
    if I cought your problem, this method should help you. I use it to expand the tree.
    private void expand(JTree tree, DefaultMutableTreeNode node) {
              if (!node.getAllowsChildren()) {
                   return;
              tree.expandPath(new TreePath(node.getPath()));
              for (int step = 0; step < node.getChildCount(); step++) {
                   expand(tree, (DefaultMutableTreeNode)node.getChildAt(step));
         }you can call the method like this:
    expand(tree, (DefaultMutableTreeNode)tree.getModel().getRoot());, tree is an instance of JTree class :-)
    LP

  • JTree expanding

    Hi,
    I have a little problem with expanding JTree. I have created UI with levelbuttons, which sould expand jTree to next sublevel and collapse jTree back to higher level. The first time I press the expanding button all works fine, because I can set all the rows I want to expand, in this case all rows with addSelectionInterval method ( addSelectionInterval(0, jTree.getRowCount()) ). The problem is, how do I know the rows of next sublevel to expand. Collapsing the current sublevel rows is also a problem. How can get the row indexes of current level?

    Can you put your code here?
    The following may be a solution:
    TreePath treepath =tree.getPathForRow(int row) ; // row is the one you know;
      DefaultMutableTreeNode node=(DefaultMutableTreeNode)(treepath.getLastPathComponent());
      DefaultMutableTreeNode childnode = node.getFirstChild();
      tree.expandPath(new TreePath(childnode.getPath()));

  • Autoscroll behavior during DnD in JTree, 1.4 vs 1.6

    The following code compiles under both Java 1.4 and Java 1.6. I'm wondering if anyone knows why the following actions cause different behaviors between the two versions:
    1. When the frame opens, you should see a fully-expanded tree (which, because of the small size, causes a vertical scrollbar to appear).
    2. Make a drag-and-drop gesture on the first child node ("blue"), and attempt to cause the tree to scroll down so you can drop it on the last parent node ("food").
    Under 1.6, the tree scrolls nicely as you hold the DnD gesture.
    Under 1.4, the tree does not scroll. I had some hope JTree.setAutoscrolls(true) would help, but it did not.
    Any suggestions how to get 1.4 to behave the way 1.6 does?
    Thanks for your time.
    import javax.swing.*;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeNode;
    import java.awt.*;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.io.IOException;
    import java.util.Enumeration;
    public class AutoScroll14 extends JFrame {
        public static void main(String[] args) {
            new AutoScroll14();
        public AutoScroll14() throws HeadlessException {
            super("AutoScroll 1.4");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JTree tree = new JTree();
            tree.setDragEnabled(true);
            tree.setTransferHandler(new MyTransferHandler());
            expand(tree, tree.getPathForRow(0));
            JScrollPane sp = new JScrollPane(tree);
            sp.setPreferredSize(new Dimension(300, 200));
            Container content = getContentPane();
            content.setLayout(new BorderLayout());
            content.add(sp, BorderLayout.CENTER);
            pack();
            setVisible(true);
        private void expand(JTree tree, TreePath path) {
            TreeNode node = (TreeNode) path.getLastPathComponent();
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath newPath = path.pathByAddingChild(n);
                expand(tree, newPath);
            tree.expandPath(path);
        private class MyTransferHandler extends TransferHandler {
            private DataFlavor localStringFlavor;
            private String localStringType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.String";
            private MyTransferHandler() {
                try {
                    localStringFlavor = new DataFlavor(localStringType);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            public boolean importData(JComponent comp, Transferable t) {
                if (!canImport(comp, t.getTransferDataFlavors())) {
                    return false;
                String data = null;
                try {
                    if (hasLocalStringFlavor(t.getTransferDataFlavors())) {
                        data = (String) t.getTransferData(localStringFlavor);
                    } else {
                        return false;
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                String location = null;
                if (comp instanceof JTree) {
                    location = ((JTree) comp).getSelectionPath().toString();
                System.out.println("Dropping [" + data + "] on location [" + location + "]");
                return true;
            private boolean hasLocalStringFlavor(DataFlavor[] flavors) {
                if (localStringFlavor == null) {
                    return false;
                for (int i = 0; i < flavors.length; i++) {
                    if (flavors.equals(localStringFlavor)) {
    return true;
    return false;
    public boolean canImport(JComponent comp, DataFlavor[] flavors) {
    return hasLocalStringFlavor(flavors);
    protected Transferable createTransferable(JComponent c) {
    if (c instanceof JTree) {
    String toTransfer = ((JTree) c).getSelectionPath().toString();
    System.out.println("Creating transferable [" + toTransfer + "]");
    return new StringTransferable(toTransfer);
    System.out.println("Could not create transferable");
    return null;
    public int getSourceActions(JComponent c) {
    return COPY_OR_MOVE;
    private class StringTransferable implements Transferable {
    private String data;
    private StringTransferable(String data) {
    this.data = data;
    public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] { localStringFlavor };
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return localStringFlavor.equals(flavor);
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (!isDataFlavorSupported(flavor)) {
    throw new UnsupportedFlavorException(flavor);
    return data;

    I added the class "TreeDropTarget".
    "TreeDropTarget" extends the class "DropTarget", which implements the interface "DropTargetListener".
    DropTargetListener has a few methods, that are called automatically by Swing during drag operation
    (dragOver, dragExit, drop). So we can implement "autoscroll", as well as "automatic node expansion".
    With "automatic node expansion", a collapsed node will be expanded,
    so that its children become visible and we can do a drop on them:
    package demo;
    * AutoScroll.java
    * source level 1.4
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.io.*;
    import java.util.*;
    public class AutoScroll extends JFrame {
        public static void main(String[] args) {
            new AutoScroll();
        public AutoScroll() throws HeadlessException {
            super("AutoScroll " + System.getProperty("java.version"));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JTree tree = new JTree();
            tree.setDragEnabled(true);
            tree.setTransferHandler(new MyTransferHandler());
            tree.setDropTarget(new TreeDropTarget());//<----------------------
            expand(tree, tree.getPathForRow(0));
            JScrollPane sp = new JScrollPane(tree);
            sp.setPreferredSize(new Dimension(300, 200));
            Container content = getContentPane();
            content.setLayout(new BorderLayout());
            content.add(sp, BorderLayout.CENTER);
            pack();
            setVisible(true);
        private void expand(JTree tree, TreePath path) {
            TreeNode node = (TreeNode) path.getLastPathComponent();
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath newPath = path.pathByAddingChild(n);
                expand(tree, newPath);
            tree.expandPath(path);
        private class MyTransferHandler extends TransferHandler {
            private DataFlavor localStringFlavor;
            private String localStringType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.String";
            private AutoScroll.MyTransferHandler.StringTransferable transferable;
            private MyTransferHandler() {
                try {
                    localStringFlavor = new DataFlavor(localStringType);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            protected void exportDone(JComponent comp, Transferable t, int action) {
                if (t == null) {
                    t = transferable;
                if (!canImport(comp, t.getTransferDataFlavors())) {
                    return;
                String data = null;
                try {
                    if (hasLocalStringFlavor(t.getTransferDataFlavors())) {
                        data = (String) t.getTransferData(localStringFlavor);
                    } else {
                        return;
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                String location = null;
                if (comp instanceof JTree) {
                    location = ((JTree) comp).getSelectionPath().toString();
                System.out.println("Dropping [" + data + "] on location [" + location + "]");
                return;
            private boolean hasLocalStringFlavor(DataFlavor[] flavors) {
                if (localStringFlavor == null) {
                    return false;
                for (int i = 0; i < flavors.length; i++) {
                    if (flavors.equals(localStringFlavor)) {
    return true;
    return false;
    public boolean canImport(JComponent comp, DataFlavor[] flavors) {
    return hasLocalStringFlavor(flavors);
    protected Transferable createTransferable(JComponent c) {
    if (c instanceof JTree) {
    String toTransfer = ((JTree) c).getSelectionPath().toString();
    System.out.println("Creating transferable [" + toTransfer + "]");
    transferable = new StringTransferable(toTransfer);
    return transferable;
    System.out.println("Could not create transferable");
    return null;
    public int getSourceActions(JComponent c) {
    return COPY_OR_MOVE;
    private class StringTransferable implements Transferable {
    private String data;
    private StringTransferable(String data) {
    this.data = data;
    public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[]{localStringFlavor};
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    return localStringFlavor.equals(flavor);
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (!isDataFlavorSupported(flavor)) {
    throw new UnsupportedFlavorException(flavor);
    return data;
    class TreeDropTarget extends DropTarget {
    public TreeDropTarget() {
    super();
    public void dragOver(DropTargetDragEvent dtde) {
    JTree tree = (JTree) dtde.getDropTargetContext().getComponent();
    Point loc = dtde.getLocation();
    updateDragMark(tree, loc);
    autoscroll(tree, loc);
    super.dragOver(dtde);
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(JTree tree, Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = tree.getVisibleRect();
    Rectangle inner = new Rectangle(
    outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(
    cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    tree.scrollRectToVisible(scrollRect);
    public void updateDragMark(JTree tree, Point location) {
    int row = tree.getRowForPath(tree.getClosestPathForLocation(location.x, location.y));
    TreePath path = tree.getPathForRow(row);
    if (path != null) {
    markNode(tree, location);
    private void markNode(JTree tree, Point location) {
    TreePath path = tree.getClosestPathForLocation(location.x, location.y);
    if (path != null) {
    if (lastRowBounds != null) {
    Graphics g = tree.getGraphics();
    g.setColor(Color.white);
    g.drawLine(lastRowBounds.x, lastRowBounds.y,
    lastRowBounds.x + lastRowBounds.width, lastRowBounds.y);
    tree.setSelectionPath(path);
    tree.expandPath(path);
    private Rectangle lastRowBounds;
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);

  • Jtree expandPath is not working

    Hi All,
    I am performing following opertion on jtree
    First i am taking path of selected jtree node.
    i am updating jtree
    then i am trying to expand jtree on the basis of selected path.
    but it is not getting expanded at all.pls help
    code --->
    TreePath treePath=tree.getSelectionPath().getParentPath();
    // below line refreshing tree with new value
    TreeStructure.CreateTreeStructure(connDialog.getConnection(), tree, connDialog.getServerName().getText());
    tree.expandPath(treePath);
    // tree.setSelectionPath(treePath);
    tree.setVisible(true);

    do u got the solution for ur problem?
    if no
    this thread show the error source
    http://forum.java.sun.com/thread.jspa?threadID=674858
    else
    tell me the solution

  • JTree open folder on single click

    I have a custom tree that expands JTree and would like the folders to open/close on a single click rather than a double click (per user requirements). Should I do this with a mouse listener and based on the node do something, or is there another way? Also, how can I programatically toggle a folder node opened/closed state?
    Thanks!

    I have a custom tree that expands JTree and would
    like the folders to open/close on a single click
    rather than a double click (per user requirements).
    Should I do this with a mouse listener and based on
    the node do something, or is there another way? Also,
    how can I programatically toggle a folder node
    opened/closed state?
    Thanks!Here's one way:
    someTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent e) {
                    if (!someTree.isExpanded(someTree.getSelectionModel().getLeadSelectionRow())) {
                        someTree.expandPath(e.getNewLeadSelectionPath());
            });

  • Wanted: (complete!) implementation of TreeModel backed by a DOM document

    originally triggered by a question over at stackOverFlow
    http://stackoverflow.com/questions/5579580/expand-jtree-at-last-modified-area
    turns out I need such a beast as well - parallelism of requirements :-)
    The emphasis is on "complete" (or at least nearly so): the most important issue is to react to changes in the Document by firing of the appropriate TreeModelEvent. Most (including some home-brewn in my knowledgebase <g>) do nothing at all in that respect, implementing the notification is "left to the reader".
    The nearest I have seen so far is DOMTreeModel:
    http://www.pbjar.org/docs/src/org/pbjar/dom/DOMTreeModel.java
    which registers itself only for DOMSubTreeModified and -AttrChanged and always reacts by firing a treeStructureChanged. Technically, I could add the finer-grained notifications (-NodeRemoved etc ... which are deprecated in dom3, but that's not relevant right now) - but for two reasons:
    a) I'm lazy <g> - if there is something out in the wild, I would love to go from there (or ideally even use unchanged)
    b) I'm fairly inexperienced in the dom world, so bound to ... sigh ... make even more mistakes than in homely Swing-related problems
    Any input highly welcome!
    CU
    Jeanette

    originally triggered by a question over at stackOverFlow
    http://stackoverflow.com/questions/5579580/expand-jtree-at-last-modified-area
    turns out I need such a beast as well - parallelism of requirements :-)
    The emphasis is on "complete" (or at least nearly so): the most important issue is to react to changes in the Document by firing of the appropriate TreeModelEvent. Most (including some home-brewn in my knowledgebase <g>) do nothing at all in that respect, implementing the notification is "left to the reader".
    The nearest I have seen so far is DOMTreeModel:
    http://www.pbjar.org/docs/src/org/pbjar/dom/DOMTreeModel.java
    which registers itself only for DOMSubTreeModified and -AttrChanged and always reacts by firing a treeStructureChanged. Technically, I could add the finer-grained notifications (-NodeRemoved etc ... which are deprecated in dom3, but that's not relevant right now) - but for two reasons:
    a) I'm lazy <g> - if there is something out in the wild, I would love to go from there (or ideally even use unchanged)
    b) I'm fairly inexperienced in the dom world, so bound to ... sigh ... make even more mistakes than in homely Swing-related problems
    Any input highly welcome!
    CU
    Jeanette

  • Expanding a JTree Node on selection

    Hi,
    I have a need to expand the node on selection in a JTree. I would like all the children to be recursively expanded and selected.
    I believe the code lies somewhere with in JTree's TreeSelectionListener.
    The code I have is as follows
    tree.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent evt)
    TreePath[] paths = evt.getPaths();
    for (int i=0; i<paths.length; i++)
    if (evt.isAddedPath(i))
    DataNode node = (DataNode)paths.getLastPathComponent();
    ArrayList aList = node.children();
    if( !aList.isEmpty() )
    for(int j = 0; j<aList.size(); j++)
    TreePath tp = paths[i].pathByAddingChild(aList.get(j));
    System.out.println(tp);
    tree.expandPath(tp);
    }//for
    }//public void ValueChanged
    This does not seem to solve the problem..
    Your comments or help is very much appreciated..
    thanks
    S

    it does work for me (i do it in an action). what doesn't work for you?
    thomas
      public RecursiveExpander() {
        menu = new JPopupMenu();
        JMenuItem expand = new JMenuItem("Expand Recursive");
        expand.addActionListener(this);
        menu.add(expand);
      public void mousePressed(MouseEvent e) {
        theTree = (JTree)e.getSource();
        currentPath = theTree.getPathForLocation(e.getX(), e.getY());
        if ((currentPath != null) &&
            !((TreeNode)currentPath.getLastPathComponent()).isLeaf() &&
            (e.getModifiers() == InputEvent.BUTTON3_MASK)) {
          menu.show(theTree, e.getX(), e.getY());
      public void actionPerformed(ActionEvent ae) {
        new Thread(this).start();
      public void run() {
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        try { expand(currentPath); }
        catch (OutOfMemoryError oom) {
          System.gc();
          System.err.println("RecursiveExpander: " + oom);
          JOptionPane.showMessageDialog(null, "RecursiveExpander: " + oom, "Error", JOptionPane.ERROR_MESSAGE);
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      private void expand(TreePath path) {
        theTree.expandPath(path);
        TreeNode start = (TreeNode)path.getLastPathComponent();
        for (int i = 0; i < start.getChildCount(); i++) {
          TreeNode node = start.getChildAt(i);
          if (!node.isLeaf()) {
            expand(path.pathByAddingChild(node));
    }

Maybe you are looking for