Expand treenode on clientclick

Hi all,
I want to extend a tree in such a way that when a user clicks the text of a treenode, the node expands or collapses, just as it would when you click the triangle in front of the treenode.
I want to do this on the client side, because all the data in the tree is sent over to the client the first time, so I don't want additional server roundtrips.
Is this possible?

Hi Prakash,
I have already created the tree, and it is working fine. In my tree, the leaves are links, and the nodes are not. The only way I have to expand a node is to click the tiny triangle in front of it. If you click the text of the node, then nothing happens. What I want is when you click the text, the node expands or collapses.
There is a javascript function in the result html which collapses or expands nodes in the tree. This function is called when you click a triangle in front of a treenode.
If I want to use this function, then I need to know the generated id of the treenode at design-time (which is a parameter of the javscript function), which I don't.
Johan

Similar Messages

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

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

  • TreeNode Silence

    I don't see solutions to the problem I am having. I cannot seem to disable user's ability to manually expand treenodes (I tried attaching an empty listener to the nodes so that nothing would happen - it failed to work).
    In addition I cannot programmatically expand them myself. The only way it works is by setVisible method in a callback for a button.
    If I try and expand them in prepareRender() it will not expand.
    These methods don't seem to work:
    t.setSelected(id); <-- what is it supposed to do to the selected node?
    t.setExpanded(true);<--Should expand the tree, right?
    t.setExpandOnSelect(false);<--Should stop user's from expanding

    If this is still a problem, try reposting on the Tree and Tree Node Components - Threadinar7 thread http://forum.sun.com/jive/thread.jspa?threadID=102657. There's an active discussion going on about Trees, so you're more likely to get some response over there.

  • Bursting with EBIZ12 and Listner Process

    Hi All,
    We are using BI Publisher with R12 Instance. We are using bursting to break the BIG XML file for the Employee data
    by manager and sending it to multiple desitnations and it is moving fine.
    We need to acheive the following also along with the bursting of the file :
    a) Store Individual File XML data into file system & corresponding Manager name and ID in table for retreival later.
    i ) Where can we plug this code ? Will the Listener Hook Provides have handle to each file XML data ?
    ii) How can we register the Listener hook with Standard Concurrent Program ( as we using the standard Bursting program in 5.6.3)?
    Any other approaches / pointers will be helpful.
    Regards,
    Abhishek

    a) Yes, listeners would work.
    i ) yes and no, the bursting engine prune's the doc and the xml disappears after the next delivery.
    ii) see below. super easy. you need to implement the bursting interface and java concurrent program.
    Here's an example homeslice of the *[Burst Designer| http://web.me.com/beth.wiggins/ike/bipublisher/BurstDesignerDist/launch.html]* creates a tree using the listeners:
    package bipublisher.burst.listener;
    import java.awt.Desktop;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.util.Enumeration;
    import java.util.Properties;
    import java.util.Vector;
    import java.util.logging.Level;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeNode;
    import javax.swing.tree.TreePath;
    import oracle.apps.xdo.batch.BurstingListener;
    import oracle.apps.xdo.batch.DocumentProcessor;
    import oracle.apps.xdo.common.log.Logger;
    import oracle.apps.xdo.common.log.XDOLogImpl;
    * @author ike
    public class BurstDesignerListener implements BurstingListener, Runnable {
        private javax.swing.JTextArea logTextArea;
        private JTree tree;
        private String burstControlFileLocation = "";
        private String testFileLocation = "";
        String tempdir = System.getProperty("java.io.tmpdir");
        private DefaultTreeModel model;
        private Properties properties;
        DefaultMutableTreeNode top = new DefaultMutableTreeNode();
        DefaultMutableTreeNode request = null;
        DefaultMutableTreeNode delivery = null;
        DefaultMutableTreeNode attachmentsDtm = null;
        static Logger logger;
        public BurstDesignerListener() {
            super();
        public void run() {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                redirectXdoLogStreams(out);
                model = (DefaultTreeModel) tree.getModel();
                top = (DefaultMutableTreeNode) model.getRoot();
                DocumentProcessor dp = new DocumentProcessor(burstControlFileLocation, testFileLocation, tempdir);
                dp.setConfig(properties);
                dp.registerListener(this);
                dp.process();
            } catch (Exception e) {
                Logger.log(e);
            } finally {
                try {
                    out.flush();
                    out.close();
                //logTextArea.append(bao.toString());
                } catch (IOException ex) {
                    java.util.logging.Logger.getLogger(BurstDesignerListener.class.getName()).log(Level.SEVERE, null, ex);
        public void beforeProcess() {
            logger.log("LISTENER:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Start of Bursting Process", 1);
            tree.setEnabled(false);
        public void beforeProcessRequest(int requestIndex) {
            logger.log("LISTENER:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Start of Process Request ID" + requestIndex, 1);
            request = new DefaultMutableTreeNode("Request ID: " + requestIndex);
            top.add(request);
        public void beforeProcessDocument(int requestIndex, int documentIndex) {
            logger.log("LISTENER:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Start of Process Document", 1);
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Request Index " + requestIndex, 1);
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Document Index " + documentIndex, 1);
        public void beforeDocumentDelivery(int requestIndex, int documentIndex, String deliveryId) {
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ========Start of Delivery", 1);
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Request Index " + requestIndex, 1);
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Document Index " + documentIndex, 1);
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: DeliveryId " + deliveryId, 1);
            delivery = new DefaultMutableTreeNode("Delivery ID: " + deliveryId);
            request.add(delivery);
        public void afterProcess() {
            logger.log("LISTENER:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::End of Bursting Process\r\n", 1);
            expandAll(tree, true);
            tree.setEnabled(true);
        public void afterProcessRequest(int requestIndex) {
            logger.log("LISTENER:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::End of Process Request ID" + requestIndex + "\r\n", 1);
        //logTextArea.append("End of Process Request ID" + requestIndex + "\r\n");
        public void afterProcessDocument(int requestIndex, int documentIndex, Vector documentOutputs) {
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ========End of Process Document", 1);
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Outputs :" + documentOutputs, 1);
        public void afterDocumentDelivery(int requestIndex, int documentIndex, String deliveryId, Object deliveryObject, Vector attachments) {
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ========End of Delivery", 1);
            logger.log("LISTENER::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Attachments : " + attachments, 1);
            Vector<String> attachments2 = attachments;
            for (String str : attachments2) {
                attachmentsDtm = new DefaultMutableTreeNode(str);
                delivery.add(attachmentsDtm);
        public String getTempdir() {
            return tempdir;
        public void setTempdir(String tempdir) {
            this.tempdir = tempdir;
        public String getBurstControlFileLocation() {
            return burstControlFileLocation;
        public void setBurstControlFileLocation(String burstControlFileDir) {
            this.burstControlFileLocation = burstControlFileDir;
        public String getTestFileLocation() {
            return testFileLocation;
        public void setTestFileLocation(String testFileDir) {
            this.testFileLocation = testFileDir;
        public JTextArea getTextArea() {
            return logTextArea;
        public void setTextArea(JTextArea textArea) {
            this.logTextArea = textArea;
        public JTree getTree() {
            return tree;
        public void setTree(JTree tree) {
            this.tree = 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);
        public Properties getProperties() {
            return properties;
        public void setProperties(Properties properties) {
            this.properties = properties;
        private void updateTextArea(final String text) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    logTextArea.append(text);
        private void redirectXdoLogStreams(ByteArrayOutputStream out) {
            out = new ByteArrayOutputStream() {
                @Override
                public void write(int b) {
                    updateTextArea(String.valueOf((char) b));
                @Override
                public void write(byte[] b, int off, int len) {
                    updateTextArea(new String(b, off, len));
                @Override
                public void write(byte[] b) throws IOException {
                    write(b, 0, b.length);
            //System.setOut(new PrintStream(out, true));
            //System.setErr(new PrintStream(out, true));
            XDOLogImpl fileLog = new XDOLogImpl();
            // bao = new ByteArrayOutputStream();
            fileLog.setDestination(out);
            Logger.setLog(fileLog);
            Logger.setLevel(Logger.STATEMENT);
        public void displayDocument() {
            if (Desktop.isDesktopSupported()) {
                Desktop desktop = Desktop.getDesktop();
                // Now enable buttons for actions that are supported.
                URI uri = null;
                try {
                    uri = new URI("file:///Users/ike/Desktop/corporate_examples/SALES.pdf");
                    desktop.browse(uri);
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                } catch (URISyntaxException use) {
                    use.printStackTrace();
        private void updateTextArea(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
        public void run() {
        logTextArea.append(text);
        private void redirectSystemStreams() {
        OutputStream out = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
        updateTextArea(String.valueOf((char) b));
        @Override
        public void write(byte[] b, int off, int len) throws IOException {
        updateTextArea(new String(b, off, len));
        @Override
        public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
        System.setOut(new PrintStream(out, true));
        System.setErr(new PrintStream(out, true));
    Hope that helps!  If it does please give me the points!
    If your looking to test bursting I have an application that can help you design the bursting control file and run it. Keep in mind it still in beta. You'll be able to get your test scenerios much faster if you use my tool. It's free, so why not!
    Click here: *[Burst Designer| http://web.me.com/beth.wiggins/ike/bipublisher/BurstDesignerDist/launch.html | A free tool to design Burst Control Files - by Ike Wiggins]*
    if you want to see what you can do with the bursting designer look at the video: *[Burst Designer Video| http://web.me.com/beth.wiggins/ike/bipublisher/BurstingDesignerDemoComputer.m4v]*
    Ike Wiggins
    http://bipublisher.blogspot.com

  • A JTree... What are the possibilities for...

    removing the actual navigation icons, lines etc., but keeping the actual form of a tree? This might sound a little silly since it only will show as normal text formatted as a tree structure, but I could use this functionality nevertheless.
    Looking forward to hearing some helpful replies (hopefully ;-)
    TIA.
    /Kasper

    Here's a start. If you find a better way to remove the lines be sure to post it.import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.plaf.basic.BasicTreeUI;
    import java.util.Enumeration;
    public class Test2 extends JFrame {
      public Test2() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        UIManager.put("Tree.hash",Color.white);  // Invisible lines - I hate this
        JTree jt = new JTree();
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        ((BasicTreeUI)jt.getUI()).setExpandedIcon(null);   
        ((BasicTreeUI)jt.getUI()).setCollapsedIcon(null);
        DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)jt.getCellRenderer();
        renderer.setLeafIcon(null);
        renderer.setClosedIcon(null);
        renderer.setOpenIcon(null);
        expandAll(jt, new TreePath(jt.getModel().getRoot()), true);
        jt.addTreeWillExpandListener(new TreeWillExpandListener() {
          public void treeWillCollapse(TreeExpansionEvent tse) throws ExpandVetoException {
            throw new ExpandVetoException(tse);
          public void treeWillExpand(TreeExpansionEvent tse) throws ExpandVetoException {
            throw new ExpandVetoException(tse);
        setSize(300,300);
      private void expandAll(JTree tree, TreePath parent, boolean expand) {
        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);
        if (expand) { // Expansion or collapse must be done bottom-up
          tree.expandPath(parent);
        } else {
          tree.collapsePath(parent);
      public static void main(String[] args) { new Test2().setVisible(true); }
    }

  • Make all leaf visible in JTree

    I haved tryied to make my jtree totaly expanded but with no success.
    The code belowe is what i tride with, butt all my leafs do not expand just to
    the las node.
    Are there realy no method for this?
    * expandAll
    * Expands / collaps a 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);
    System.out.println("c "+parent);
    /**********************************************************/

    This code works for me. I hope it works for you also.
    I have a JTree called myTree with a TreeModel called myTreeModel. The solution has two methods. The first method "expandTree()" is what you call to show all the branches. This method will get the root node from the tree model and then call the method that exands all the paths, "expandEntireTree(TreeNode)". This recursive method will call itself for each of it's children.
    Good luck,
    Kevin Ford
    public void expandTree() {
         expandEntireTree((DefaultMutableTreeNode) myTreeModel.getRoot());
    private void expandEntireTree(TreeNode tNode) {
         TreePath tp=new TreePath(((DefaultMutableTreeNode)tNode).getPath());
         myTree.expandPath(tp);
         for(int i = 0; i < tNode.getChildCount(); i++) {
              expandEntireTree(tNode.getChildAt(i));
    }

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

  • Problem with JTree in expanded mode?

    Hi I have a JTree and I have added few nodes to it. Now when i run my program it is displaying all the nodes in the expanded mode. but at some point of time i need to add few more nodes. when i am am adding nodes to the root node when the tree in expanded mode the newly added nodes are not visible. They are not getting added. what could be the problem? how do i add nodes to the tree when in expanded mode as well as remove few nodes when in expanded mode?
    My code is as follows.
    import java.awt.BorderLayout;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Main extends JFrame{
         private DefaultMutableTreeNode top;
         public JTree mainTree;
         public Main(){
              super();
              JDesktopPane dp=new JDesktopPane();          
              dp.setLayout(new BorderLayout());
              top =new DefaultMutableTreeNode("All Active Nodes");                    
              mainTree=new JTree(top);          
              JScrollPane mtsp=new JScrollPane(mainTree);
              dp.add(mtsp,BorderLayout.CENTER);
              this.setContentPane(dp);          
              this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);          
              this.setSize(300, 550);
              this.setVisible(true);
         public static void main(String[]args)throws Exception{
              Main as=new Main();
              DefaultMutableTreeNode top=as.getTop();
              DefaultMutableTreeNode node=new DefaultMutableTreeNode("murali");
              top.add(node);
              as.mainTree.expandRow(0);          
              Thread.sleep(10000);
              System.out.println("there");
              DefaultMutableTreeNode node1=new DefaultMutableTreeNode("murali12");
              top.add(node1);
          * @return the top
         public DefaultMutableTreeNode getTop() {
              return top;
    }

    I got the solution. The solution is to invoke nodesWereInserted(TreeNode node, int[] childIndices) this on treeModel after adding nodes are removing nodes.

  • How do i expand all the nodes in a jtree

    Hi,
    I am working on a project where i need to expand all the nodes of a jtree i have tried a few different ways but it never seems to expand all the nodes..
    I would be very greatful if someone could point me in the right direction
    cheers
    Mary

    you could use the following method that expands nodes recursively
    expandNode( myTree, myRootNode, new TreePath( myRootNode ) );
    public static void expandNode( JTree tree, TreeNode node, TreePath path ) {
        tree.expandPath( path );
        int i = node.getChildCount( );
        for ( int j = 0; j< i; j++ ) {
            TreeNode child = node.getChildAt( j );
            expandNode( tree, child , path.pathByAddingChild( child ) );
    }

  • Need to expand tree by passing treeId thr URL not by clicking manually.

    Sub: Need to expand tree by passing Id thr URL.
    Hi,
    Here i have Library.java and ajaxTree.jsf files (collected from Jboss richfaces)
    There is having a list of artist .
    If u click on a particular artistname then the respective albums(with their checkboxes) will expand and show like a treenode.
    just look at d url : "http://localhost:8080/richfaces-demo-3.2.1.GA/richfaces/tree.jsf?c=tree&albumIds=1001,1002,1005,1008,1009,1010&client=0"
    I m passing album Ids and clientId in url browser and receiving in d Library.java.
    I need to expand the required client tree to show albums without clicking on artistname rather by passing the clientId from Url.
    I thnk one EventHandling class( PostbackPhaseListener.java ) is responsible for expanding but I m unable to understand.
    How can I do it.
    Plz help asap.
    /###############ajaxTree.jsf##########Start##############/
    <ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:a4j="http://richfaces.org/a4j"
    xmlns:rich="http://richfaces.org/rich"
    xmlns:c="http://java.sun.com/jstl/core">
         <p>This tree uses "ajax" switch type, note that for collapse/expand operations it will be Ajax request to the server. You may see short delay in this case.</p>
         <h:form>     
              <rich:tree style="width:300px" value="#{library.data}" var="item" nodeFace="#{item.type}">
                   <rich:treeNode type="artist" >
                        <h:outputText value="#{item.name}" />
                        </rich:treeNode>
                   <rich:treeNode type="album" >
                        <h:selectBooleanCheckbox value="#{item.selected}"/>
                        <h:outputText value="#{item.title}" />
                   </rich:treeNode>
              </rich:tree>
              <h:commandButton value="Update" />
         </h:form>
    </ui:composition>
    /###############ajaxTree.jsf##########End##############/
    /************************Library.java*********Start****************/
    package org.richfaces.demo.tree;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.StringTokenizer;
    import javax.servlet.http.HttpServletRequest;
    import javax.faces.context.FacesContext;
    import org.richfaces.model.TreeNode;
    public class Library implements TreeNode {
         private static final long serialVersionUID = -3530085227471752526L;
         private Map artists = null;
         private Object state1;
         private Object state2;
         private Map getArtists() {
              if (this.artists==null) {
                   initData();
              return this.artists;
         public void addArtist(Artist artist) {
              addChild(Long.toString(artist.getId()), artist);
         public void addChild(Object identifier, TreeNode child) {
              getArtists().put(identifier, child);
              child.setParent(this);
         public TreeNode getChild(Object id) {
              return (TreeNode) getArtists().get(id);
         public Iterator getChildren() {
              return getArtists().entrySet().iterator();
         public Object getData() {
              return this;
         public TreeNode getParent() {
              return null;
         public boolean isLeaf() {
              return getArtists().isEmpty();
         public void removeChild(Object id) {
              getArtists().remove(id);
         public void setData(Object data) {
         public void setParent(TreeNode parent) {
         public String getType() {
              return "library";
         private long nextId = 0;
         private long getNextId() {
              return nextId++;
         private Map albumCache = new HashMap();
         private Map artistCache = new HashMap();
         private Artist getArtistByName(String name, Library library) {
              Artist artist = (Artist)artistCache.get(name);
              if (artist==null) {
                   artist = new Artist(getNextId());
                   artist.setName(name);
                   artistCache.put(name, artist);
                   library.addArtist(artist);
              return artist;
         private Album getAlbumByTitle(String title, Artist artist) {
              Album album = (Album)albumCache.get(title);
              if (album==null) {
                   album = new Album(getNextId());
                   album.setTitle(title);
                   albumCache.put(title, album);
                   artist.addAlbum(album);
              return album;
         private void initData() {
              artists = new HashMap();
              InputStream is = this.getClass().getClassLoader().getResourceAsStream("org/richfaces/demo/tree/data.txt");
              ByteArrayOutputStream os = new ByteArrayOutputStream();
              byte[] rb = new byte[1024];
              int read;
              HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
         //     System.out.println("request.getParameter(param) "+request.getParameter("param"));
              //System.out.println("request.getParameter(client) "+request.getParameter("client"));
              //System.out.println("request.getParameter() "+request.getParameter("c"));
              try {
                   do {
                        read = is.read(rb);
                        if (read>0) {
                             os.write(rb, 0, read);
                   } while (read>0);
                   String buf = os.toString();
                   StringTokenizer toc1 = new StringTokenizer(buf,"\n");
                        String str1 = request.getParameter("albumIds");
                        int clientId1 =Integer.parseInt( request.getParameter("client"));
                   while (toc1.hasMoreTokens()) {
                        String str = toc1.nextToken();
                        StringTokenizer toc2 = new StringTokenizer(str, "\t");
                        String artistName = toc2.nextToken();
                        String albumTitle = toc2.nextToken();
                        String songTitle = toc2.nextToken();
                        toc2.nextToken();
                        toc2.nextToken();
                        String albumYear = toc2.nextToken();
                        Artist artist = getArtistByName(artistName,this);
                        Album album = getAlbumByTitle(albumTitle, artist);
                        String portfolios[] = new String[100];
                        Integer portfoliosId[] = new Integer[100];
                        int i = 0;
                        StringTokenizer st = new StringTokenizer(str1, ",");
                        while (st.hasMoreTokens()) {
                        portfolios[i] = st.nextToken();
                        if((songTitle.equals(portfolios))&&(!(songTitle == ""))){
                                  //System.out.println("ifff");
                                  album.setSelected(true);
                        i++;
                        album.setYear(new Integer(albumYear));
              } catch (IOException e) {
                   throw new RuntimeException(e);
         public Object getState1() {
              return state1;
         public void setState1(Object state1) {
              this.state1 = state1;
         public Object getState2() {
              return state2;
         public void setState2(Object state2) {
              this.state2 = state2;
         public void walk(TreeNode node, List<TreeNode> appendTo, Class<? extends TreeNode> type) {
              if (type.isInstance(node)){
                   appendTo.add(node);
              Iterator<Map.Entry<Object, TreeNode>> iterator = node.getChildren();
              System.out.println("walk node.getChildren() "+node.getChildren());
              while(iterator.hasNext()) {
                   walk(iterator.next().getValue(), appendTo, type);
         public ArrayList getLibraryAsList(){
              ArrayList appendTo = new ArrayList();
              System.out.println("getLibraryAsList appendTo "+appendTo);
              walk(this, appendTo, Song.class);
              return appendTo;
    /************************Library.java*********End****************/
    /************************PostbackPhaseListener.java*********Start****************/
    package org.richfaces.treemodeladaptor;
    import java.util.Map;
    import javax.faces.context.ExternalContext;
    import javax.faces.context.FacesContext;
    import javax.faces.event.PhaseEvent;
    import javax.faces.event.PhaseId;
    import javax.faces.event.PhaseListener;
    public class PostbackPhaseListener implements PhaseListener {
         public static final String POSTBACK_ATTRIBUTE_NAME = PostbackPhaseListener.class.getName();
         public void afterPhase(PhaseEvent event) {
         public void beforePhase(PhaseEvent event) {
              FacesContext facesContext = event.getFacesContext();
              Map requestMap = facesContext.getExternalContext().getRequestMap();
              requestMap.put(POSTBACK_ATTRIBUTE_NAME, Boolean.TRUE);
         public PhaseId getPhaseId() {
              return PhaseId.APPLY_REQUEST_VALUES;
         public static boolean isPostback() {
              FacesContext facesContext = FacesContext.getCurrentInstance();
              if (facesContext != null) {
                   ExternalContext externalContext = facesContext.getExternalContext();
                   if (externalContext != null) {
                        return Boolean.TRUE.equals(
                                  externalContext.getRequestMap().get(POSTBACK_ATTRIBUTE_NAME));
              return false;
    /************************PostbackPhaseListener.java*********End****************/
    Edited by: rajesh_forum on Sep 17, 2008 6:13 AM
    Edited by: rajesh_forum on Sep 17, 2008 6:18 AM

    Hi
    Can somebody please look into this?
    Thanks
    Raj
    Edited by: RajICWeb on Aug 9, 2009 4:38 AM

  • How can i change the expand level of nodes in treeView1 according to numericupdown value change ?

    I have this method:
    void ExpandToLevel(TreeNodeCollection nodes, int level)
    if (level > 0)
    foreach (TreeNode node in nodes)
    node.Expand();
    ExpandToLevel(node.Nodes, level - 1);
    I added now a new method:
    void CollapseToLevel(TreeNodeCollection nodes, int level)
    if (level > 0)
    foreach (TreeNode node in nodes)
    node.Collapse();
    CollapseToLevel(node.Nodes, level - 1);
    Then in the numericupdown changed value event i did:
    decimal oldValue;
    private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    if (numericUpDown1.Value > oldValue)
    ExpandToLevel(treeView1.Nodes, (int)numericUpDown1.Value);
    else
    CollapseToLevel(treeView1.Nodes, (int)numericUpDown1.Value);
    oldValue = numericUpDown1.Value;
    When i expand change the numericupdown value up it's expand it fine level by level. But when i collapse it back when changing the numericupdown value back down if i was at value 4 and now changed to value 3 all the nodes collapsed back to root.
    I want it to collapse only by one level from 4 to 3 to 2 to 1 when the vlaue is 0 then collapse back to root.
    The collapse is not working good.

    Hi,
    You don't need to loop from the start to collapse it.
    Just issue the collapse on the current node; if its not collapsible then nothing will happen.
    treeView1.SelectedNode.Collapse();
    Happy coding.
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • JTree with XML content expand/collapse problem

    Hello all,
    I'm having this very weird problem with a JTree I use to display the contents of an XML file. I use the DOM parser (and not JDOM since I want the application to run as an applet as well, and don't want to have any external libraries for the user to download) and have a custom TreeModel and TreeNode implementations to wrap the DOM nodes so that they are displayed by the JTree.
    I have also added a popup menu in the tree, for the user to be able to expand/collapse all nodes under the selected one (i.e. a recursive method).
    When expandAll is run, everything works fine and the children of the selected node are expanded (and their children and so on).
    However, after the expansion when I run the collapseAll function, even though the selected node collapses, when I re-expand it (manually not by expandAll) all of it's children are still fully open! Even if I collapse sub-elements of the node manually and then collapse this node and re-expand it, it "forgets" the state of it's children and shows them fully expanded.
    In other words once I use expandAll no matter what I do, the children of this node will be expanded (once I close it and re-open it).
    Also after running expandAll the behaviour(!) of the expanded nodes change: i have tree.setToggleClickCount(1); but on the expanded nodes I need to double-click to collapse them.
    I believe the problem is related to my implementations of TreeModel and TreeNode but after many-many hours of trying to figure out what's happening I'm desperate... Please help!
    Here's my code:
    public class XMLTreeNode implements TreeNode 
         //This class wraps a DOM node
        org.w3c.dom.Node domNode;
        protected boolean allowChildren;
        protected Vector children;
        //compressed view (#text).
         private static boolean compress = true;   
        // 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",
        static final int ELEMENT_TYPE =   1;
        static final int ATTR_TYPE =      2;
        static final int TEXT_TYPE =      3;
        static final int CDATA_TYPE =     4;
        static final int ENTITYREF_TYPE = 5;
        static final int ENTITY_TYPE =    6;
        static final int PROCINSTR_TYPE = 7;
        static final int COMMENT_TYPE =   8;
        static final int DOCUMENT_TYPE =  9;
        static final int DOCTYPE_TYPE =  10;
        static final int DOCFRAG_TYPE =  11;
        static final int NOTATION_TYPE = 12;
        // The list of elements to display in the tree
       static String[] treeElementNames = {
            "node",
      // Construct an Adapter node from a DOM node
      public XMLTreeNode(org.w3c.dom.Node node) {
        domNode = node;
      public String toString(){
           if (domNode.hasAttributes()){
                return domNode.getAttributes().getNamedItem("label").getNodeValue();
           }else return domNode.getNodeName();      
      public boolean isLeaf(){ 
           return (this.getChildCount()==0);
      boolean treeElement(String elementName) {
          for (int i=0; i<treeElementNames.length; i++) {
            if ( elementName.equals(treeElementNames)) return true;
    return false;
    public int getChildCount() {
         if (!compress) {   
    return domNode.getChildNodes().getLength();
    int count = 0;
    for (int i=0; i<domNode.getChildNodes().getLength(); i++) {
    org.w3c.dom.Node node = domNode.getChildNodes().item(i);
    if (node.getNodeType() == ELEMENT_TYPE
    && treeElement( node.getNodeName() ))
    // Note:
    // Have to check for proper type.
    // The DOCTYPE element also has the right name
    ++count;
    return count;
    public boolean getAllowsChildren() {
         // TODO Auto-generated method stub
         return true;
    public Enumeration children() {
         // TODO Auto-generated method stub
         return null;
    public TreeNode getParent() {
         // TODO Auto-generated method stub
         return null;
    public TreeNode getChildAt(int searchIndex) {
    org.w3c.dom.Node node =
    domNode.getChildNodes().item(searchIndex);
    if (compress) {
    // Return Nth displayable node
    int elementNodeIndex = 0;
    for (int i=0; i<domNode.getChildNodes().getLength(); i++) {
    node = domNode.getChildNodes().item(i);
    if (node.getNodeType() == ELEMENT_TYPE
    && treeElement( node.getNodeName() )
    && elementNodeIndex++ == searchIndex) {
    break;
    return new XMLTreeNode(node);
    public int getIndex(TreeNode tnode) {
         if (tnode== null) {
              throw new IllegalArgumentException("argument is null");
         XMLTreeNode child=(XMLTreeNode)tnode;
         int count = getChildCount();
         for (int i=0; i<count; i++) {
              XMLTreeNode n = (XMLTreeNode)this.getChildAt(i);
              if (child.domNode == n.domNode) return i;
         return -1; // Should never get here.
    public class XMLTreeModel2 extends DefaultTreeModel
         private Vector listenerList = new Vector();
         * This adapter converts the current Document (a DOM) into
         * a JTree model.
         private Document document;
         public XMLTreeModel2 (Document doc){
              super(new XMLTreeNode(doc));
              this.document=doc;
         public Object getRoot() {
              //System.err.println("Returning root: " +document);
              return new XMLTreeNode(document);
         public boolean isLeaf(Object aNode) {
              return ((XMLTreeNode)aNode).isLeaf();
         public int getChildCount(Object parent) {
              XMLTreeNode node = (XMLTreeNode) parent;
    return node.getChildCount();
         public Object getChild(Object parent, int index) {
    XMLTreeNode node = (XMLTreeNode) parent;
    return node.getChildAt(index);
         public int getIndexOfChild(Object parent, Object child) {
    if (parent==null || child==null )
         return -1;
              XMLTreeNode node = (XMLTreeNode) parent;
    return node.getIndex((XMLTreeNode) child);
         public void valueForPathChanged(TreePath path, Object newValue) {
    // Null. no changes
         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 );
         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 );
    The collapseAll, expandAll code (even though I m pretty sure that's not the problem since they work fine on a normal JTree):
        private void collapseAll(TreePath tp){
             if (tp==null) return;
             Object node=tp.getLastPathComponent();
             TreeModel model=tree.getModel();
             if (!model.isLeaf(node)){
                  tree.collapsePath(tp);
                  for (int i=0;i<model.getChildCount(node);i++){
                  //for (int i = node.childCount()-4;i>=0;i--){
                       collapseAll(tp.pathByAddingChild(model.getChild(node,i)));
                  tree.collapsePath(tp);
        private void expandAll(TreePath tp){
             if (tp==null) return;
             Object node=tp.getLastPathComponent();
             TreeModel model=tree.getModel();
             if (!model.isLeaf(node)){
                  tree.expandPath(tp);
                  for (int i=0;i<model.getChildCount(node);i++){
                  //for (int i = node.childCount()-4;i>=0;i--){
                       expandAll(tp.pathByAddingChild(model.getChild(node,i)));

    Hi,
    Iam not facing this problem. To CollapseAll, I do a tree.getModel().reload() which causes all nodes to get collapsed and remain so even if I reopen them manually.
    Hope this helps.
    cheers,
    vidyut

  • Using ComboBox as an editor for treenodes

    I have a customized combobox editor for editing treenodes. The treenodes may or may not editable based on a particular condition in the userobject at each node.
    The node and the combobox are rendered fine but as soon as I select an item from the combobox, i see the following error messages in the stack trace and the code goes into an infinite loop :
    Exception occurred during event dispatching:
    java.lang.StackOverflowError
         at java.lang.ref.Reference.<init>(Reference.java:198)
         at java.lang.ref.FinalReference.<init>(FinalReference.java:19)
         at java.lang.ref.Finalizer.<init>(Finalizer.java:69)
         at java.lang.ref.Finalizer.register(Finalizer.java:75)
         at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:883)
         at javax.swing.JComboBox.contentsChanged(JComboBox.java:950)
         at javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:79)
         at javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:86)

    Here's the code for the custom combobox editor:
    public class ScmComboBoxEditor extends DefaultCellEditor
    private JTree m_tree;
    /* private JComboBox m_comboBox;
    protected EventListenerList _treeNodeListeners = new EventListenerList();
    protected ChangeEvent changeEvent = null;
    public ScmComboBoxEditor(JTree tree, JComboBox combo)
    super(combo);
    m_tree = tree;
    setClickCountToStart(3);
    public Component getTreeCellEditorComponent(JTree tree, Object value,
                                  boolean isSelected,
                                  boolean expanded,
                                  boolean leaf, int row)
    Component comp = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
    if(comp instanceof JComboBox)
    JComboBox combo = (JComboBox)comp;
    ScmTreeNode thisNode = (ScmTreeNode)value;
    /* if(thisNode.getUserObject() instanceof ScmObject)
    ScmObject thisObj = (ScmObject)thisNode.getUserObject();
    Vector vItems = new Vector();
    vItems.addElement(thisObj);
    for(int j = 0; j < 3; j++)
    ScmObject obj = new ScmObject();
    obj.setName("Branch" + (j+1));
    vItems.addElement(obj);
    DefaultComboBoxModel comboModel = new DefaultComboBoxModel(vItems);
    combo.setModel(comboModel);
    if(thisNode.getUserObject() instanceof MappableProject)
    MappableProject thisObj = (MappableProject)thisNode.getUserObject();
    if(thisObj.hasBranches())
    Vector vItems = new Vector();
    vItems.addElement(thisObj);
    for(int j = 0; j < 3; j++)
    MappableProject obj = new MappableProject();
    obj.setName("Branch" + (j+1));
    vItems.addElement(obj);
    DefaultComboBoxModel comboModel = new DefaultComboBoxModel(vItems);
    combo.setModel(comboModel);
    else if(thisNode.getUserObject() instanceof MappableFolder)
    MappableFolder thisObj = (MappableFolder)thisNode.getUserObject();
    if(thisObj.hasBranches())
    Vector vItems = new Vector();
    vItems.addElement(thisObj);
    for(int j = 0; j < 3; j++)
    MappableProject obj = new MappableProject();
    obj.setName("Branch" + (j+1));
    vItems.addElement(obj);
    DefaultComboBoxModel comboModel = new DefaultComboBoxModel(vItems);
    combo.setModel(comboModel);
    return comp;
    public boolean isCellEditable(EventObject ev)
    boolean rv = false;
    if(ev instanceof MouseEvent)
    MouseEvent me = (MouseEvent)ev;
    System.out.println("Clicks = " + me.getClickCount());
    if(me.getClickCount() == this.getClickCountToStart())
    TreePath path = m_tree.getPathForLocation(me.getX(), me.getY());
    ScmTreeNode node = (ScmTreeNode)path.getLastPathComponent();
    if(((ScmObject)node.getUserObject()).hasBranches())
    rv = true;
    return rv;
    public boolean stopCellEditing()
    this.fireEditingStopped();
    return false;
    public void cancelCellEditing()
    this.fireEditingCanceled();
    /* public void addCellEditorListener(CellEditorListener l)
    _treeNodeListeners.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l)
    _treeNodeListeners.remove(CellEditorListener.class, l);
    protected void fireEditingStopped()
    Object[] listeners = _treeNodeListeners.getListenerList();
    for(int i = listeners.length-2; i >= 0; i-=2)
    if(changeEvent == null)
    changeEvent = new ChangeEvent(this);
    ((CellEditorListener)listeners[i+1]).editingStopped(changeEvent);
    protected void fireEditingCanceled()
    Object[] listeners = _treeNodeListeners.getListenerList();
    for(int i = listeners.length-2; i >= 0; i-=2)
    if(changeEvent == null)
    changeEvent = new ChangeEvent(this);
    ((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent);
    public void setCellEditorValue(Object value)
    m_comboBox = (JComboBox)this.editorComponent;
    m_comboBox.setSelectedItem(value);
    }

  • Help in getting current expanded node in Tree UI

    HI,
    I have a requirement to build a tree dynamically. On expanding each node I need to create sub nodes inside that. But it is always creating inside the node where the lead selection is and not inside the current expanded node. Even though I have used getTreeSelection () to get the current element.
    <b>Detailed description about the application.,</b>
    I have created a context with the following structure,
    TreeNode (0..n)
    |
    |--> ChildNode (recursive SiteTree)
    |--> Name (string)
    I have created a Tree UI Element in the view and inserted a node type 'TreeNodeType'.
    I have set the properties of the inserted node type as given bellow,
    Value Attribute in TreeNode -> Name I have assigned to 'Text' property of 'TreeNodeType'.
    Initially I have created four nodes in the init() method ., using the following code :
    for(int i=0;i<3;i++)
    IPrivateTestTreeView.ITreeNodeNode treenode=wdContext.nodeTreeNode();
    IPrivateTestTreeView.ITreeNodeElement treeelement=wdContext.createTreeNodeElement();
    treeelement.setName("Testroot:"+i);
    treenode.addElement(treeelement);
    Now I need to create sub-nodes for this dynamically.,
    I have created an action and called it in 'onLoadChildren' event of 'TreeNodeType' with the following code:
    public void OnCurrentSelection()
    IPrivateTestTreeView.ITreeNodeElement el = wdContext.nodeTreeNode().getTreeSelection();
    wdComponentAPI.getMessageManager().reportSuccess(el.getName());
    <b>
    Where this returns me only the name of LeadSelection node and not the  node which i try to expand.  </b>
    Is there anyway I can get the currently expanded node., Kindly help me out in this.
    Points will be rewarded for helpful answers. Thanks in advance.
    Regards,
    Nirmal

    HI Ayyapparaj ,
    <b>First I would like to thank you for your reply.</b>
    So it means that we cannot identify the currently expanded node in tree UI element and It will always be the lead selection node we will be able to get rite?
    Can we make the current lead selection to currently expanded node 'By Default'?
    Coming back to your solution.,
    I created a context element 'isExpanded' of type boolean inside the TreeNode.
    You said that there will be a call made to 'getter and setter' methods while we expand the node and we can set the lead selection to that element from there.
    Could you please give me some more details of how to achieve it.
    Thanks in advance.
    Regards,
    Nirmal G

Maybe you are looking for

  • In PO these fields(Pl. Deliv. Time,Goods Receipt & GR Non-Valuated) hide

    Hi, In PO in item detail in delivery tab Pl. Deliv. Time,Goods Receipt & GR Non-Valuated fields  where in screen layout document level(me21n) because i need hide, Reqd.entry , Opt. entry & Display

  • Letting VGA output TV signal

    Hey guys, I'm building an arcade cabinet and i'm trying to hook my arcade monitor up to my video card. I know it is possible to connect it directly to the video card but i have to let the VGA port output a TV signal. it's an NVidia GeForce4 MX 440. i

  • Apple ID is blocked due to security reasons. Can't unlock

    Hi, A friend of mine has an @icloud.com Apple ID. For a couple of days her account has become "blocked due to security reasons". We have no idea why, but that is besides the point. She forgot the answers to her security questions. And the only other

  • HP Designjet Z6100 printhead failure.

    I´m having the following problem: When the plotter has to print an image with some yellow density, printhead yellow / magenta begins to fail, and the printer stops printing, giving the indication that is necessary to replace the printhead magenta / y

  • Create  folder Clint machine

    Hi I want to create a folder in the Clint machine using a servlet or jsp is it possible to do, If so, could any one guide me to do this. Thankz & Regards Anbu