JTree expand

Hello,
I have got a JApplet which uses a JTree.
When a node has child nodes, i.e. when it could be expanded, I have the following problem:
If the node is selected (I use TreeSelectionModel.SINGLE_TREE_SELECTION), I can't expand it. However, if it isn't selected, I DO can.
Does somebody what could be happening?
Thank you very much
Sergio Ocio

Hi,
I'm using a JTree to display a recursive tree (jdev903preview). This works fine.
However, I have a few issues and questions regarding expanding the tree
(the +/- buttons):
1) If I set rootVisible to true, I see the accessor name in the tree root.
Setting rootVisible to false solves this. But this also removes the '+'
buttons of the first visible level in the tree! The user can only expand
these nodes by doubleclicking the icon. How do I get around this? I don't
want the accessor to be visible (why would I ever want to expose an internal
name to the user?), but I do want the '+' buttons.You may want to establish a custom cell-renderer for the Tree and take-out the "text" from the root node. Here's a sample:
jTree1.setCellRenderer(new JUTreeCellRenderer()
public java.awt.Component getTreeCellRendererComponent(javax.swing.JTree tree, Object value,
boolean sel,
boolean expanded,
boolean leaf, int row,
boolean hasFocus)
java.awt.Component cmp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus());
if (tree.getModel().getRoot() == value)
setText(""); //you can substitute any text you want here for the root node.
return cmp;
2) In the tree, the '+' buttons appear even for nodes which do not have children.
When the user clicks the '+' in front of an empty node, the '+' disappears, and
the icon changes from the 'map' icon to the 'leaf' icon. Why does it draw the
wrong icon and the '+' for empty nodes?This is because, JClient tree is bound to database and without executing individual nodes the binding does not know if the node is a leaf or a parent node. If you want to execute all nodes you may want to set the tree to expand all mode. I believe there's some swing call to "expand all nodes in a tree". BY default JClient only expands the first ViewObject in the hierarchy.
3) Is it possible to expand the entire tree by default?Again beware of the database query impact here.
Greetings,
Ivo

Similar Messages

  • JTree Expanded By Default

    Hi,
    I was wondering if there is a way to have a tree created and rendered in the completely expanded form. I am thinking along the lines that is there is a setting or a method that by default does it.
    If i am not mistaken there is a posting here in the forum to do this programatically.
    Thank You,
    -Uday

    Did you search for "JTree Expanded By Default" and saw that the answers were all about expanding the tree programatically:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=774838
    and you wanted to make double-sure there was no other way to do it?

  • JTree Expand All & Collapse All...

    Hi All,
    i hv two buttons "Expand All" & "Collapse All". If i press "Expand All" i should expand all the nodes in the all the root nodes(JTree).
    If i press "Collapse All" i sh collapse all the entries in the JTree.
    Is there any way to acheive this.
    Thanks
    ss

    Hi!
    You can try these methods where treeRoot is the root node of the tree:
    * Collapses the function group tree.
    public void collapseAll() {
    for (int i = treeRoot.getChildCount(); i > 0; i--) {
    tree.collapseRow(i);
    * Collapses the function group tree.
    public void expandAll() {
    for (int i = treeRoot.getChildCount(); i > 0; i--) {
    tree.expandRow(i);
    /Malin

  • JTree expanding problem(urgent)

    hi all,
    I am new to java and i am developing DMS where i use JTree to display folders. I am using vectors for displaying folder names and files. when i select a folder and create a folder under that, after creating it should highlight the folder where i am creating folder but in my project it is highlighting HOME folder.
    I tried tree.expandPath, tree.setSelectionPath(treepath), tree.fireTreeExpanded(treepath); but its not working.
    before this steps i am printed treepath, path is correctly printing. I dont know why the tree is not expanding....
    please give me a solution.....

    tree.scrollPathToVisible(...)

  • JTree expand programatically is not working

    jTree1.fireTreeExpanded(curTreePath);
    expandAll(jTree1, curTreePath, true);
    jTree1.expandPath(curTreePath);
    jTree1.scrollPathToVisible(curTreePath);
    jTree1.updateUI();
    jTree1.setExpandsSelectedPaths(true);
    jTree1.expandPath(curTreePath);
    expandAll(jTree1, curTreePath, true);
    for (int i = 0; i < jTree1.getRowCount(); i++)
    jTree1.expandRow(i);
    jTree1.validate();
    jTree1.repaint();
    Any help ?

    package so;
    ToDo list
    * Log timestamp and line number of at every exception.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.sql.*;
    import java.io.*;
    import java.net.*;
    import java.util.Enumeration;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import javax.swing.tree.*;
    public class SCM extends javax.swing.JFrame implements javax.swing.event.TreeExpansionListener, javax.swing.event.TreeModelListener, javax.swing.event.TreeWillExpandListener
        Connection con = null;
        java.sql.Statement stmt = null;
        ResultSet rs = null;
        PrintStream log = null;// File creation at local system, to record events, actions, errors and traces
        javax.swing.tree.TreePath curTreePath = null;
        /** Creates new form SCM */
        public SCM()
            //---------------------- Native LookandFeel Windows is expected.-------------------//
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception e)
                System.out.println("Error setting native LAF: " + e);
            //******************** Native LookandFeel Windows is expected.*******************//
            // initialising GUI containers and controls
            initComponents();
            TableCellRenderer defaultRenderer;
            defaultRenderer = jTable1.getDefaultRenderer(JLabel.class);
            jTable1.setDefaultRenderer(JLabel.class, new Label_cell(defaultRenderer));
            setState(javax.swing.JFrame.HIDE_ON_CLOSE);
            jfc.setEnabled(false);
            this.setSize(1024, 740);
            jTree1.setSize(400, this.getWidth() / 4);
            jTree1.setRootVisible(false);
            jTree1.addTreeWillExpandListener(this); // Registering jTree1 to Expand listener.
            jTree1.setCellRenderer(new TreeIconRenderer());
            try
                //-------Preparing Logger----------------//
                FileOutputStream fos = new FileOutputStream(new File(System.getProperties().getProperty("user.home") + System.getProperties().getProperty("file.separator") + "SCM-Log_" + System.currentTimeMillis()));
                log = new PrintStream(fos);
                log.println("Started Time\t\t:" + new java.util.Date().getTime());
                //*******Preparing Logger****************//
                // Initialising jTree1 with the userid and preparing the xml and loading jTree1 with xml content,
                // and expected to repeat the same while refreshing.
                //----- Rendering images for the folders and files i.e. nodes and leaves of this tree
                jTree1 = new XMLTree("215");
                //******** Rendering images for the folders and files i.e. nodes and leaves of this tree
                //Selection can only contain one path at a time, i.e. user is confined to reffere to only one node
                //or leaf at a time
                //jTree1.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION);
                this.setTitle("ZIIC-ITG SCM");// Title can be changed at any time.
            catch (IOException ioe)
                ioe.printStackTrace(log);   //logging Exception.
                //This is first level action and to be decided to go further or not by exit(0);.
        public boolean prepareCon() throws ClassNotFoundException
            try
                if (con != null && !con.isClosed())
                    return true;
                else
                    Class.forName("oracle.jdbc.driver.OracleDriver");
                    java.sql.DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                    con = java.sql.DriverManager.getConnection("jdbc:oracle:thin:@172.16.1.31:1521:soadb", "dms", "dms");
                    if (con != null && !con.isClosed())
                        return true;
            catch (java.lang.ClassNotFoundException cnfe)
                cnfe.printStackTrace(log);
            catch (SQLException se)
                se.printStackTrace(log);
            if (con != null)
                return true;
            else
                return true;
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents()
            jPopupMenu1 = new javax.swing.JPopupMenu();
            jSplitPane1 = new javax.swing.JSplitPane();
            jScrollPane1 = new javax.swing.JScrollPane();
            try
                jTree1 = new XMLTree("215");
                jScrollPane2 = new javax.swing.JScrollPane();
                jTable1 = new javax.swing.JTable();
                menuBar = new javax.swing.JMenuBar();
                fileMenu = new javax.swing.JMenu();
                openMenuItem = new javax.swing.JMenuItem();
                saveMenuItem = new javax.swing.JMenuItem();
                saveAsMenuItem = new javax.swing.JMenuItem();
                exitMenuItem = new javax.swing.JMenuItem();
                editMenu = new javax.swing.JMenu();
                cutMenuItem = new javax.swing.JMenuItem();
                copyMenuItem = new javax.swing.JMenuItem();
                pasteMenuItem = new javax.swing.JMenuItem();
                deleteMenuItem = new javax.swing.JMenuItem();
                helpMenu = new javax.swing.JMenu();
                contentsMenuItem = new javax.swing.JMenuItem();
                aboutMenuItem = new javax.swing.JMenuItem();
                //setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            }catch(Exception e){}
            jTree1.setDoubleBuffered(true);
            jTree1.setDragEnabled(true);
            jTree1.setEditable(true);
            jTree1.setFocusTraversalPolicyProvider(true);
            jTree1.setInheritsPopupMenu(true);
            jTree1.setInvokesStopCellEditing(true);
            jTree1.setLargeModel(true);
            jTree1.setMaximumSize(new java.awt.Dimension(250, 64));
            jTree1.setPreferredSize(new java.awt.Dimension(200, 64));
            jTree1.setVerifyInputWhenFocusTarget(false);
            jTree1.addMouseListener(new java.awt.event.MouseAdapter()
                public void mouseClicked(java.awt.event.MouseEvent evt)
                    jTree1MouseClicked(evt);
            jTree1.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener()
                public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt)
                    jTree1TreeCollapsed(evt);
                public void treeExpanded(javax.swing.event.TreeExpansionEvent evt)
                    jTree1TreeExpanded(evt);
            jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener()
                public void valueChanged(javax.swing.event.TreeSelectionEvent evt)
                    jTree1ValueChanged(evt);
            jScrollPane1.setViewportView(jTree1);
            jSplitPane1.setLeftComponent(jScrollPane1);
            jScrollPane2.setAutoscrolls(true);
            jScrollPane2.setDoubleBuffered(true);
            jScrollPane2.setFocusCycleRoot(true);
            jScrollPane2.setFocusTraversalPolicyProvider(true);
            jScrollPane2.setInheritsPopupMenu(true);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][]
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String []
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jTable1.addMouseListener(new java.awt.event.MouseAdapter()
                public void mouseClicked(java.awt.event.MouseEvent evt)
                    jTable1MouseClicked(evt);
            jScrollPane2.setViewportView(jTable1);
            jSplitPane1.setRightComponent(jScrollPane2);
            fileMenu.setText("File");
            openMenuItem.setText("Open");
            fileMenu.add(openMenuItem);
            saveMenuItem.setText("Save");
            fileMenu.add(saveMenuItem);
            saveAsMenuItem.setText("Save As ...");
            fileMenu.add(saveAsMenuItem);
            exitMenuItem.setText("Exit");
            exitMenuItem.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    exitMenuItemActionPerformed(evt);
            fileMenu.add(exitMenuItem);
            menuBar.add(fileMenu);
            editMenu.setText("Edit");
            cutMenuItem.setText("Cut");
            editMenu.add(cutMenuItem);
            copyMenuItem.setText("Copy");
            editMenu.add(copyMenuItem);
            pasteMenuItem.setText("Paste");
            editMenu.add(pasteMenuItem);
            deleteMenuItem.setText("Delete");
            editMenu.add(deleteMenuItem);
            menuBar.add(editMenu);
            helpMenu.setText("Help");
            contentsMenuItem.setText("Contents");
            helpMenu.add(contentsMenuItem);
            aboutMenuItem.setText("About");
            helpMenu.add(aboutMenuItem);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt)
        try
            curTreePath = evt.getPath();
            //curTreePath.getPathCount();
            //selectedNode = stPath.getPathComponent(stCount - 1);
            //TODO add your handling code here:
            if (prepareCon())
                javax.swing.tree.TreePath path = evt.getPath();
                DMETreeNode node = (DMETreeNode) path.getLastPathComponent();
                try
                    if (node != null && (node.getSerial() + "").length() > 0)
                        //stmt = con.createStatement();
                        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                        rs = stmt.executeQuery("select serial, description, file_location, status, sheet,  part, approvedby, locked, location, created_by from dms_files where owner=" + node.getSerial());
                        SCM_Tbl_model model = new SCM_Tbl_model();
                        model.setRs(rs);
                        //jTable1.setColumnModel(columnModel);
                        jTable1.setModel(model);
                        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
                        jTable1.setRowSorter(sorter);
                catch (Exception e)
                    e.printStackTrace();
            catch (ClassNotFoundException ex)
                ex.printStackTrace(log);
                Logger.getLogger(SCM.class.getName()).log(Level.SEVERE, null, ex);
        private void jTree1MouseClicked(java.awt.event.MouseEvent evt)
        // TODO add your handling code here:   
        if (evt.getButton() == evt.BUTTON3)
            jPopupMenu1.removeAll();
            javax.swing.JMenuItem expandMI = new javax.swing.JMenuItem("Expand");
            javax.swing.JMenuItem expandAllMI = new javax.swing.JMenuItem("Expand All");
            javax.swing.JMenuItem find_folderMI = new javax.swing.JMenuItem("Find Folder");
            final javax.swing.JMenuItem new_folderMI = new javax.swing.JMenuItem("New Folder");
            javax.swing.JSeparator separator1 = new javax.swing.JSeparator();
            jPopupMenu1.setSize(100, 200);
            jPopupMenu1.add(expandMI);
            jPopupMenu1.add(expandAllMI);
            jPopupMenu1.add(separator1);
            jPopupMenu1.add(find_folderMI);
            jPopupMenu1.add(new_folderMI);
            jPopupMenu1.setVisible(true);
            jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
            //expandToLast(jTree1);
            //jTree1.scrollPathToVisible(curTreePath);
            //jTree1.fireTreeExpanded(curTreePath);       
            ActionListener menuOnTree = new ActionListener()
                        public void actionPerformed(ActionEvent e)
                            if (e.getSource().equals(new_folderMI))
                                    DMETreeNode ch=new DMETreeNode("Child of "+((DMETreeNode)curTreePath.getLastPathComponent()).toString());   
                                    ((DMETreeNode) curTreePath.getLastPathComponent()).add(ch);
                                    jTree1.fireTreeExpanded(curTreePath);
                                    expandAll(jTree1, curTreePath, true);
                                    jTree1.expandPath(curTreePath);
                                    jTree1.scrollPathToVisible(curTreePath);
                                    jTree1.updateUI();
                            if (e.getActionCommand().trim().equalsIgnoreCase("Expand"))
                                jTree1.setExpandsSelectedPaths(true);
                                jTree1.expandPath(curTreePath);
                                expandAll(jTree1, curTreePath, true);
                                for (int i = 0; i < jTree1.getRowCount(); i++)
                                    jTree1.expandRow(i);
                                jTree1.validate();
                                jTree1.repaint();
                                System.out.println(((DMETreeNode) curTreePath.getLastPathComponent()).getSerial());
                                expandToLast(jTree1);
                                System.out.println(jTree1.getModel().getRoot().toString());
                                ((XMLTree)jTree1).expandAll(true);
                                expandToLast(jTree1);
            expandMI.addActionListener(menuOnTree);
            expandAllMI.addActionListener(menuOnTree);
            find_folderMI.addActionListener(menuOnTree);
            new_folderMI.addActionListener(menuOnTree);
    public void expandAll(JTree tree, boolean expand)
            TreeNode root = (TreeNode) tree.getModel().getRoot();
            // Traverse tree from root
            expandAll(tree, new TreePath(root), expand);
        private void expandAll(JTree tree, TreePath parent, boolean expand)
            // Traverse children
            TreeNode node = (TreeNode) parent.getLastPathComponent();
            if (node.getChildCount() >= 0)
                for (Enumeration e = node.children(); e.hasMoreElements();)
                    TreeNode n = (TreeNode) e.nextElement();
                    TreePath path = parent.pathByAddingChild(n);
                    //System.out.println(path.toString());
                    expandAll(tree, path, expand);
            // Expansion or collapse must be done bottom-up
            if (expand)
                tree.expandPath(parent);
            else
                tree.collapsePath(parent);
    public void expandToLast(JTree tree)
            // expand to the last leaf from the root
            DefaultMutableTreeNode root;
            root = (DefaultMutableTreeNode) tree.getModel().getRoot();
            tree.scrollPathToVisible(new TreePath(root.getLastLeaf().getPath()));
            //System.out.println(""+root.getLastLeaf().getPath().toString());
        public void expandToLast(JTree tree)
            TreeModel data = tree.getModel();
            Object node = data.getRoot();
            if (node == null)
                return;
            TreePath p = new TreePath(node);
            while (true)
                int count = data.getChildCount(node);
                if (count == 0)
                    break;
                node = data.getChild(node, count - 1);
                p = p.pathByAddingChild(node);
            tree.scrollPathToVisible(p);
        private void jTree1TreeExpanded(javax.swing.event.TreeExpansionEvent evt)
        // TODO add your handling code here:
            System.out.println("@447");
        private void jTree1TreeCollapsed(javax.swing.event.TreeExpansionEvent evt) {                                    
        // TODO add your handling code here:
        private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                            
            System.exit(0);
        @SuppressWarnings("static-access")
        private void jTable1MouseClicked(java.awt.event.MouseEvent evt)                                    
            // TODO add your handling code here:
            jPopupMenu1.removeAll();
            jPopupMenu1.setVisible(true);
            //Prepare Menu items based the event and the user, and the item clicked on i.e.
            javax.swing.JMenuItem menuItem = new javax.swing.JMenuItem("Add A doc", KeyEvent.VK_T);
            jPopupMenu1.add(menuItem);
            ActionListener al = new ActionListener()
                        public void actionPerformed(ActionEvent e)
                            jfc.updateUI();
                            jfc.showOpenDialog(jTable1);
                            jTable1.setValueAt(jfc.getSelectedFile().getAbsolutePath(), jTable1.getSelectedRow(), jTable1.getSelectedColumn());
                            jfc.setDialogTitle("Choose only fmx files");
                            try
                                if (jfc.getSelectedFile().getAbsolutePath() != null)
                                    java.io.File f = new java.io.File(jfc.getSelectedFile().getAbsolutePath());
                                    if (f.exists())
                                        // Start FTP process.
                                        SCM_FTP ftp = new SCM_FTP();
                                        ftp.connect("ziicsrv11", 21, "z11902", "ziicit");
                                        ftp.bin();
                                        // Change to a new working directory on the FTP server.
                                        ftp.cwd("bin");
                                        // Upload some files.
                                        log.println("FTP Start: " + System.currentTimeMillis());
                                        ftp.stor(f);
                                        ftp.disconnect();
                                        log.println("FTP Done: " + System.currentTimeMillis());
                            catch (java.io.IOException ioe)
                                log.println("File is not Found");
                                ioe.printStackTrace(log);
            menuItem.addActionListener(al);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
            jPopupMenu1.setSize(100, 200);
            if (evt.getButton() == evt.BUTTON3)//evt.isPopupTrigger()
                jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
         * @param args the command line arguments
        public static void main(String args[])
            java.awt.EventQueue.invokeLater(new Runnable()
                        public void run()
                            SCM s = new SCM();
                            s.setVisible(true);
                            //s.setState(s.HIDE_ON_CLOSE);
                            s.setAlwaysOnTop(true);
                            SystemTrayTest st = new SystemTrayTest();
                            st.setControl(s);
                            st.showFrame();
        // Variables declaration - do not modify                    
        private javax.swing.JMenuItem aboutMenuItem;
        private javax.swing.JMenuItem contentsMenuItem;
        private javax.swing.JMenuItem copyMenuItem;
        private javax.swing.JMenuItem cutMenuItem;
        private javax.swing.JMenuItem deleteMenuItem;
        private javax.swing.JMenu editMenu;
        private javax.swing.JMenuItem exitMenuItem;
        private javax.swing.JMenu fileMenu;
        private javax.swing.JMenu helpMenu;
        private javax.swing.JPopupMenu jPopupMenu1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JSplitPane jSplitPane1;
        private javax.swing.JTable jTable1;
        private javax.swing.JTree jTree1;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JMenuItem openMenuItem;
        private javax.swing.JMenuItem pasteMenuItem;
        private javax.swing.JMenuItem saveAsMenuItem;
        private javax.swing.JMenuItem saveMenuItem;
        // End of variables declaration                  
        private javax.swing.JFileChooser jfc = new javax.swing.JFileChooser();
        public void treeExpanded(TreeExpansionEvent event)
        public void treeCollapsed(TreeExpansionEvent event)
        public void treeNodesChanged(TreeModelEvent e)
        public void treeNodesInserted(TreeModelEvent e)
        public void treeNodesRemoved(TreeModelEvent e)
        public void treeStructureChanged(TreeModelEvent e)
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException
    }

  • Jtree expand all not working

    I have a very large jtree, that at it second level gets loaded from a JDOm file.
    The problem is I am having a problem expanding all the nodes under a
    particular node. I need an expandAll method. Nothing I have tried has
    expanded beyond the child level.
    After a few permutations my code right now is
    public void expandAll(DefaultMutableTreeNode node)
    Enumeration list = node.breadthFirstenumeraion();
    while (list.hasMoreElements())
    TreePath treePath = new
    TreePath(((DefaultMutableTreeNode)list.nextElement()).getPath()))
    tree_m.expandPath(treePath);
    Am i missing something about expandPath?
    I even use the code from JTree example to the reload the model.
    But it still only shows the nodes children, not the children's children....etc.

    Hi!
    You can try these methods where treeRoot is the root node of the tree:
    * Collapses the function group tree.
    public void collapseAll() {
    for (int i = treeRoot.getChildCount(); i > 0; i--) {
    tree.collapseRow(i);
    * Collapses the function group tree.
    public void expandAll() {
    for (int i = treeRoot.getChildCount(); i > 0; i--) {
    tree.expandRow(i);
    /Malin

  • How to make a Jtree expandable

    Hi have a JTree and when I expand the tree and catch an exption hence not adding any children I would like the node that I have expanded to autamatically be collapsed, and ready for a future expand, as I have a situation were a node in the tree might not yet have any children (the children will be added dynamically).
    I would like to handel the 9iexeption in such a way that the tree is ready for use and has the "+ sign available" to the user,
    at the moomemt it thincks there are no chldren and has no "+ " or "-" sign so no future expand is posible
    please help !!!!

    hentchocan wrote:
    I want to make a JTree that has a TextArea nodes. So each child when expanded shows a text area containing some information . Can any one provide example of such behaviour .
    Best Regards,Here the reply button works.

  • JTree expand problem

    Let's say a tree has 3 children, and each children has a hierarchy of subtrees. Is there any way to just expand one children and its subtrees??
    root
    |_A
    |_SUBTREE
    |_B
    |_SUBTREE
    |_C
    |_SUBTREE
    If I do the following, it will expand the whole big tree.
    JTree tree;
    //etc...
    1) /** Expand the tree */
    for (int i=0; i<tree.getRowCount(); i++)
    tree.expandRow(i);
    If I do this, it own expands the first 6 children (including the subtrees of each children)
    2) /** Expand the tree */
    for (int i=0; i<6; i++)
    tree.expandRow(i);
    any ideas?? please help!!

    I think u mistook my point. Let's say a JTree has 3 children as follows:
    and each child has its own tree hierarchy.
    root
    |_SUBTREE1
    |_SUBTREE2
    |_SUBTREE3
    All I want is when the user click a particular tree node, the whole subtree will expand.
    I tried the following, but it only expands the child of the tree node I selected.
    public void treeExpanded(TreeExpansionEvent evt)
    {     System.out.println("treeExpanded...");
              TreePath path = evt.getPath();
              int pathCount = path.getPathCount();
              System.out.println(pathCount);
    for (int i=0; i<pathCount; i++)
    tree.expandPath(path);
    Any ideas???

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

  • JTree expand sub Node

    Hi, ALL
    I have created a JTree, ---Root
    |--One
    |--Two
    It display perfect. however, when I added some sub node under
    |-One
    it did, however, it is not expanded. I want to expanded subnode after
    It is added automatically, Do not need user to push mouse or do some action. how to implement it?
    Thanks in advanced

    there's a method named expandPath(...) in JTree?!

  • Making a JTree expanded by default

    I made a JTree and was wondering if there is a way to make it so that the JTree is totally expanded by default instead of having to click the circles to expand each spot.

        // If expand is true, expands all nodes in the tree.
        // Otherwise, collapses all nodes in the tree.
        public void expandAll(JTree tree, boolean expand) {
            TreeNode root = (TreeNode)tree.getModel().getRoot();
            // Traverse tree from root
            expandAll(tree, new TreePath(root), expand);
        private void expandAll(JTree tree, TreePath parent, boolean expand) {
            // Traverse children
            TreeNode node = (TreeNode)parent.getLastPathComponent();
            if (node.getChildCount() >= 0) {
                for (Enumeration e=node.children(); e.hasMoreElements(); ) {
                    TreeNode n = (TreeNode)e.nextElement();
                    TreePath path = parent.pathByAddingChild(n);
                    expandAll(tree, path, expand);
            // Expansion or collapse must be done bottom-up
            if (expand) {
                tree.expandPath(parent);
            } else {
                tree.collapsePath(parent);
        }

  • Changing JTree Expand And collapsed Icons

    Hi,
    can anyone tell me how to change the expanded and collpased icons on a JTree, i am using windows look and feel, and i don't know how to change the '+' and '-' icons, the other icons are changed using the DefaulTreeCellRenderer, but i haven't found a way to achieve my goal....
    thanks

    In the beginning of your main method you write :
    try {
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
         UIManager.put("Tree.collapsedIcon",new ImageIcon("plus.gif");
         UIManager.put("Tree.expandedIcon",new ImageIcon("minus.gif");
    catch (Exception exc) {
         System.err.println("Error loading L&F: " + exc);
    }And you change the name of the images with the wanted ones.
    Denis

  • Jtree - expand leafs to the LEFT

    hello !
    how can I change the direction on the JTree -
    currenlty the tree is expanding left to right .
    I would like to expand it right to left , so it will fix languages like arabic.
    (it will looks like mirror view of the current tree)
    thanks.

    JTree.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

  • JTree expand/collapse

    how to check if a node in a JTree is expanded???

    In my JTree there are couple of nodes which are all initially expanded.
    User collapses couple of nodes in the JTree while others are still expanded.
    Then, if user deleted a node from a JTree would like to keep all expanded nodes as expanded and collapsed nodes as collapsed.
    How to do this?
    Thanks.

  • JTree Expanded Icon

    How can I change the icon in the JTree of JavaHelps TOC when I expand or close the node. I understand that I need to give the tree a different cell renderer but can't find out where to do that. Does anyone have an example of this?
    Thanks,
    Rich
    Developer

    Thankyou for your help. I am getting a lot closer. There is something I am still missing though. I am sure I am setting the cell renderer to the tree now. The problem is that it is not effecting the images at all. Here is my code for this. Can you see what I am doing wrong?
    private void jButtonHelp_ActionPerformed()
              try
                   ClassLoader loader = this.getClass().getClassLoader();
                   URL helpURL = HelpSet.findHelpSet(loader, "helpset.hs");
                   m_hs = new HelpSet(loader, helpURL);
                   HelpBroker hb = m_hs.createHelpBroker();
                   JHelp jhelp = new JHelp(m_hs);
                   JHelpTOCNavigator jhtoc = null;
                   hb.setDisplayed(true);
                   new CSH.DisplayHelpFromSource(hb);
                   for(Enumeration enum = jhelp.getHelpNavigators();enum.hasMoreElements();)
                        try
                             jhtoc = (JHelpTOCNavigator)enum.nextElement();
                             break;
                        catch(Exception ee){}
                   if(jhtoc != null)
                        JTree aTree = getNavTree(jhtoc);
                        aTree.setCellRenderer(new HelpTreeRenderer());
                        aTree.updateUI();
                        jhelp.updateUI();
              catch (Exception e)
                   System.out.println("Help Exception " + e.getMessage());
    class HelpTreeRenderer extends DefaultTreeCellRenderer{
         public Component getTreeCellRendererComponent(JTree tree, Object value,
              boolean selected, boolean expanded, boolean leaf, int row,
              boolean hasFocus) {
              try
                   DefaultTreeCellRenderer treeCellRender = (DefaultTreeCellRenderer)
                   super.getTreeCellRendererComponent(tree, value, selected, expanded,
              leaf, row, hasFocus);
                   DefaultMutableTreeNode node =(DefaultMutableTreeNode)value;
                   if(node.getLevel() == 1) treeCellRender.setIcon(getImageDepartment());
              catch (Exception e)
                   System.out.println("HelpTreeRenderer Inner Class WIP Viewer Exception " + e.getMessage());
              return this;
    }

Maybe you are looking for