Expand a path in JTree

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

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

Similar Messages

  • Problem Expanding certain paths in a JTree

    I am working with a JTree and trying to do the following:
    My JTree is initially defined using the following code:
    rootNode = new DefaultMutableTreeNode();
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    tree = new JTree(treeModel);
    //treeListener = new TreeSelectionListener();
    tree.addTreeSelectionListener(treeListener);
    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
    renderer.setLeafIcon(null);
    tree.setCellRenderer(renderer);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setShowsRootHandles(true);
    tree.setAutoscrolls(true);
    tree.setExpandsSelectedPaths(true);
    When a user selects a node, and presses some button, I get and save the current path (of the selected component) like this:
    TreePath currentPath = tree.getSelectionPath();
    Then I do some action on it, then repopulate the JTree
    I have the following code at the bottom of the JTree populating method in an effort to expand the path in the tree which was last selected:
    tree.expandPath(currentPath);
    tree.setVisible(true);
    tree.updateUI();
    The problem is that when the tree repopulates, it stays completely collapsed, and I can't seem to figure out how automatically make it viewable in an expanded state (I don't want the user to have to go expand each expandable node by clicking beside it)
    Does anyone know how to either expand the whole tree from the very beginning, or expand just the selected path?
    Thanks in advance for your help,
    Noha

    To expand on path there is jtree.expandPath(treepath);
    To expand the whole tree, I wrote a recursive method.

  • Expanding path on JTree

    Hi.
    I add a node to the default tree model and an event gets fired back to the listener (in this case the JTree itself). I then expand the path so as to show the new node to the user. A gap appears between the new node and the node in another branch below the new node. If I force a re-render (like with updateUI - erk!) the tree is drawn fine, otherwise its now. See the diagram below. If this a common problem and how do you fix it? Many thanks!
    A +
    |
    +----B
    |
    +----C
    Now I insert a node D, and I get:
    A +
    |
    +----B
    | |
    | +----D
    | <------- big gap :-(
    |
    +----C                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class Test extends JFrame {
      JTree jt = new JTree();
      JButton jb = new JButton("Add");
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.add(new JScrollPane(jt),BorderLayout.CENTER);
        jt.setExpandsSelectedPaths(true);
        JButton jb = new JButton("Add");
        content.add(jb, BorderLayout.SOUTH);
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            TreePath tp = jt.getSelectionPath();
            if (tp!=null) {
              DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
              DefaultMutableTreeNode newDmtn = new DefaultMutableTreeNode("Something");
              dmtn.add(newDmtn);
              ((javax.swing.tree.DefaultTreeModel)jt.getModel()).nodeStructureChanged(dmtn);
              jt.setSelectionPath(new TreePath(newDmtn.getPath()));
        setSize(200, 300);
        show();
      public static void main(String args[]) { new Test(); }
    }

  • Path in JTree

    How should I know where I click in jTree, actually I want to read the value of the selected node in JTree.
    Thanks
    Raheel

    You can a implement a selection listener and get the node each time a selection is made.
    Or from the API you can glean the method
    Object      getLastSelectedPathComponent()
    Returns the last path component in the first node of the current selection.

  • Path and JTree?

    Hi everybody !!!
    I would like to know how I can get the complete path of the JTree. I use the getLastSelectedPathComponent()) but it display only the folder. Do you know a method that can display the path of the folder?
    tree.addMouseListener(new MouseAdapter()
         public void mousePressed(MouseEvent e)
              if (e.getModifiers()==e.BUTTON1_MASK) // Bouton gauche
                             planche.affichageGraphique(tree.getLastSelectedPathComponent());
              else if(e.getModifiers()==e.BUTTON3_MASK) // Bouton droit
                             f_temps.setVisible(true);
    Thanks !!!

    jTree.getSelectionPath()

  • How do I remove expand / collapse icon for JTree empty folders

    Hi
    I am using a JTree as a file system browser. I use DefaultMutableTreeNode nodes.
    I have a problem with empty folders.
    Empty folders show the expand / collapse icon, leading the user to believe there are sub-directories. When the user double-clicks the folder, the expand / collapse icon goes away. This is a "haha-gotcha" glitch that I really don't want my users to have to continually deal with.
    So, how might I get my JTree to not show the expand / collapse icon for empty folders?
    Thanks
    Wayne

    Maybe I can use the FileSystemView isTraversable(File f) method in my TreeCellRenderer class to check if anything is in the directory.
    But I still need to know how to disable the expand / collapse icon for such a node.

  • Change behaviour of Expand/collapse icon in JTree

    Want to change the behaviour of Expand/collapse icon in a JTree. Need help with the same. Thanks.

    Check: Hide and show region

  • How can I expand the path of keywords in the metadata inspector?

    In the metadata view I see the keywords at the leaf level, but I want to see the full path in order to delete one of multiple keywords of the same name (at leaf level).
    To better explain: Let's say there are two leafs "other"; if both are applied to a single version then they appear as one "other" in the inspector. If I delete the only "other" in the inspector then it deletes both types, not just the one. Obviously something is keeping track of the difference, because when I delete the keyword of type1's "other", it complains that a version has it. Yet, when I delete it, the type 2's "other" remains in the inspector's keyword list.
    In a nutshell: I simply want to delete a keyword for a given path, whether it be from the inspector or some other method. Besides, it would be nice to see which "other" it is in the inspector. Surely there is a preference I missed.

    You can't (afaik).
    Aperture's implementation of Keywording in general, and hierarchical Keywords in particular, would benefit from a rather complete rewrite.
    I strongly suggest renaming your keywords so that you have NO identical Keywords at different levels of your Keyword hierarchy.  (Perhaps "OtherPerson", "OtherFlower".)
    If you do this before deleting any Keywords, the "same name different Keyword" problem will disappear, both for applying Keywords and for deleting Keywords.  Renaming Keywords is live -- if you rename one in the Keywords HUD, it will be renamed for every Image to which it is assigned.
    Note that the Keyword Rule in the Filter HUD will show you a more complete path when needed.  You should be able to filter for Keywords by path if two Keywords of the same name are present in the container being filtered.
    (This is from memory -- I can't check right now.)

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

  • JTree Sub Folder of Tree Expanding Incorrectly

    The first time I try to expand a node It gets Expanded. But then when I try to expand the subfolders It does not happen. I am simply not understanding how to go about. The program based on the lines of the 2nd Example of Java Swing 2nd edition(Mathew Robinson) of the Trees Chapter
    import java.awt.BorderLayout;
    import java.io.File;
    import java.util.Vector;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeExpansionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    public class FileSystemTree extends JFrame {
         public static final ImageIcon iconComputer = new ImageIcon("computer.gif");
         public static final ImageIcon iconDisk = new ImageIcon("disk.gif");
         private JTree jtree = null;
         private DefaultTreeModel defaultTreeModel = null;
         private JTextField jtfStatus;
         public FileSystemTree() {
              super("FileSystem Tree");
              setSize(500, 500);
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(
                        new NodeIconData(iconComputer, null, "My Comp"));
              DefaultMutableTreeNode node;
              File[] roots = File.listRoots(); //Different disk Drives for the System
              for (int i = 0; i < roots.length; i++) {
                   node = new DefaultMutableTreeNode(new NodeIconData(iconDisk, null,
                             new FileNode(roots)));
                   root.add(node);
                   node.add(new DefaultMutableTreeNode(new Boolean(true)));
              defaultTreeModel = new DefaultTreeModel(root);
              jtree = new JTree(defaultTreeModel);
              jtree.getSelectionModel().setSelectionMode(
                        TreeSelectionModel.SINGLE_TREE_SELECTION);
              jtree.putClientProperty("JTree.linestyle", "Angled");
              jtree.addTreeExpansionListener(new FSDirectoryExpansionListener());
              jtree.setShowsRootHandles(true);
              jtree.setEditable(false);
              jtfStatus = new JTextField();
              jtfStatus.setEditable(false);
              getContentPane().add(new JScrollPane(jtree), BorderLayout.CENTER);
              getContentPane().add(jtfStatus, BorderLayout.SOUTH);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
         DefaultMutableTreeNode getTreeNode(TreePath path) {
              return (DefaultMutableTreeNode) path.getLastPathComponent();
         FileNode getFileNode(DefaultMutableTreeNode node) {
              if (node == null) {
                   return null;
              Object obj = node.getUserObject();
              if (obj instanceof NodeIconData) {
                   obj = ((NodeIconData) obj).getObject();
              if (obj instanceof FileNode) {
                   return (FileNode) obj;
              } else {
                   return null;
         class FSDirectoryExpansionListener implements TreeExpansionListener {
              public void treeCollapsed(TreeExpansionEvent event) {
              public void treeExpanded(TreeExpansionEvent event) {
                   final DefaultMutableTreeNode node = getTreeNode(event.getPath());
                   final FileNode fileNode = getFileNode(node);
                   Thread runner = new Thread() {
                        public void run() {
                             if (fileNode != null && fileNode.expand(node)) {
                                  Runnable runnable = new Runnable() {
                                       public void run() {
                                            defaultTreeModel.reload(node);
                                  SwingUtilities.invokeLater(runnable);
                   runner.start();
         public static void main(String args[]) {
              new FileSystemTree();
    class NodeIconData {
         private Icon normalIcon;
         private Icon expandedIcon;
         private Object data;
         public NodeIconData(Icon icon, Object data) {
              this.normalIcon = icon;
              this.expandedIcon = null;
              this.data = data;
         public NodeIconData(Icon icon, Icon expandedIcon, Object data) {
              this.normalIcon = icon;
              this.expandedIcon = expandedIcon;
              this.data = data;
         public Object getObject() {
              return data;
         public Icon getExpandedIcon() {
              return (expandedIcon != null ? expandedIcon : normalIcon);
         public Icon getNormalIcon() {
              return normalIcon;
         public String toString() {
              return data.toString();
    class FileNode {
         protected File file;
         public FileNode(File file) {
              this.file = file;
         public File getFile() {
              return file;
         public String toString() {
              return file.getName().length() > 0 ? file.getName() : file.getPath();
         public boolean expand(DefaultMutableTreeNode parent) {
              DefaultMutableTreeNode flag = (DefaultMutableTreeNode) parent
                        .getFirstChild();
              if (flag == null) // No flag
                   return false;
              Object obj = flag.getUserObject();
              if (!(obj instanceof Boolean))
                   return false; // Already expanded
              parent.removeAllChildren(); // Remove Flag
              File[] files = listFiles();
              if (files == null)
                   return true;
              Vector v = new Vector();
              for (int k = 0; k < files.length; k++) {
                   File f = files[k];
                   if (!(f.isDirectory()))
                        continue;
                   FileNode1 newNode = new FileNode1(f);
                   boolean isAdded = false;
                   for (int i = 0; i < v.size(); i++) {
                        FileNode1 nd = (FileNode1) v.elementAt(i);
                        if (newNode.compareTo(nd) < 0) {
                             v.insertElementAt(newNode, i);
                             isAdded = true;
                             break;
                   if (!isAdded)
                        v.addElement(newNode);
              for (int i = 0; i < v.size(); i++) {
                   FileNode1 nd = (FileNode1) v.elementAt(i);
                   IconData idata = new IconData(DirTree.ICON_FOLDER,
                             DirTree.ICON_EXPANDEDFOLDER, nd);
                   DefaultMutableTreeNode node = new DefaultMutableTreeNode(idata);
                   parent.add(node);
                   if (nd.hasSubDirs())
                        node.add(new DefaultMutableTreeNode(new Boolean(true)));
              return true;
         public boolean hasSubDirs() {
              File[] files = listFiles();
              if (files == null) {
                   return false;
              for (int i = 0; i < files.length; i++) {
                   if (files[i].isDirectory()) {
                        return true;
              return false;
         public int compareTo(FileNode toCompare) {
              return file.getName().compareToIgnoreCase(toCompare.file.getName());
         public File[] listFiles() {
              if (!(file.isDirectory())) {
                   return null;
              try {
                   return file.listFiles();
              } catch (Exception e) {
                   e.printStackTrace();
                   return null;

    Try this one:
    * FileTree.java
    * author: roar
    import java.io.FileFilter;
    import java.io.*;
    import java.util.List;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    public class FileTree extends JTree implements TreeWillExpandListener {
        private static class FileComparator implements Comparator<File> {
            public int compare(File f1, File f2) {
                if (f1.isDirectory() ^ f2.isDirectory()) {
                    return (f1.isDirectory() ? -1 : 1);
                return f1.getName().compareToIgnoreCase(f2.getName());
        private static class DirectoryFilter implements FileFilter {
            public boolean accept(File f) {
                return f.isDirectory();
        private static class AcceptAllFilter implements FileFilter {
            public boolean accept(File f) {
                return true;
        private static final Comparator<File> FILE_COMPARATOR = new FileComparator();
        /** A FileFilter, that accepts directories only */
        public static final FileFilter DIRECTORY_FILTER = new DirectoryFilter();
        /** A FileFilter that accepts all types of files and directories*/
        public static final FileFilter ACCEPT_ALL_FILTER = new AcceptAllFilter();
        /** The current FileFilter */
        protected FileFilter filter = null;
        public FileTree() {
            // look for home directory
            File homeDir = FileSystemView.getFileSystemView().getHomeDirectory();
            // set root element
            DefaultMutableTreeNode root = new DefaultMutableTreeNode(homeDir);
            // set model with root
            DefaultTreeModel model = new DefaultTreeModel(root);
            setModel(model);
            setShowsRootHandles(true);
            // set TreeCellRenderer.
            setCellRenderer(new FileTreeRenderer());
            // expand root
            expandPath(root);
            // add listener
            addTreeWillExpandListener(this);
            // etc ...
            getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
         * Expands a path in the tree.
         * @param d The parent node
        private void expandPath(final DefaultMutableTreeNode d) {
            d.removeAllChildren();
            File[] tempf = ((File) d.getUserObject()).listFiles();
            List<File> files = Arrays.asList(tempf);
            Collections.sort(files, FILE_COMPARATOR);
            DefaultMutableTreeNode temp = null;
            for (File file : files) {
                if (filter != null && !filter.accept(file)) {
                    continue;
                temp = new DefaultMutableTreeNode(file);
                if (file.isDirectory()) {
                    temp.add(new DefaultMutableTreeNode(null));
                d.add(temp);
            ((DefaultTreeModel) getModel()).reload(d);
         * Sets the FileFilter and resets the tree.
         * @param f The new FileFilter
        public void setFileFilter(FileFilter f) {
            filter = f;
            expandPath((DefaultMutableTreeNode) getModel().getRoot());
         * Returns the current FileFilter
         * @return The FileFilter
        public FileFilter getFileFilter() {
            return filter;
        public File getSelectedFile() {
            TreePath selectionPath = getSelectionPath();
            if (selectionPath == null) {
                return null;
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
            return (File) node.getUserObject();
        public void treeWillCollapse(TreeExpansionEvent e) {
            ((DefaultMutableTreeNode) (e.getPath().getLastPathComponent())).removeAllChildren();
            ((DefaultMutableTreeNode) (e.getPath().getLastPathComponent())).add(new DefaultMutableTreeNode(null));
        public void treeWillExpand(TreeExpansionEvent e) {
            expandPath((DefaultMutableTreeNode) (e.getPath().getLastPathComponent()));
        public static void main(String[] args) throws Exception {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            final JFrame f = new JFrame("Choose File");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final FileTree chooser = new FileTree();
            chooser.setFileFilter(FileTree.DIRECTORY_FILTER);
            JScrollPane scrp = new JScrollPane(chooser);
            Border empty = BorderFactory.createEmptyBorder(5, 5, 2, 5);
            scrp.setBorder(BorderFactory.createCompoundBorder(empty, scrp.getBorder()));
            JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            bottom.add(new JButton(new AbstractAction("OK") {
                public void actionPerformed(ActionEvent e) {
                    File file = chooser.getSelectedFile();
                    String s = "'" + file + "'";
                    if (file == null) {
                        s = "nothing";
                    JOptionPane.showMessageDialog(f, "There was " + s + " selected.");
                    f.dispose();
            f.add(scrp);
            f.add(bottom, BorderLayout.SOUTH);
            f.setSize(300, 400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class FileTreeRenderer extends DefaultTreeCellRenderer {
        private FileSystemView fsv = FileSystemView.getFileSystemView();
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            Object user = ((DefaultMutableTreeNode) value).getUserObject();
            if (user instanceof File) {
                File f = (File) user;
                String name = f.getName();
                setIcon(fsv.getSystemIcon(f));
                setText(fsv.getSystemDisplayName(f));
            return this;
    }You can also use ACCEPT_ALL_FILTER;
    chooser.setFileFilter(FileTree.ACCEPT_ALL_FILTER);Edited by: Andre_Uhres on Jan 27, 2008 10:02 AM

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

  • Trouble with JTree's and autmoatically expanding nodes

    I am writing an application which uses a JTree as a method of browsing through a certain structure (like a file system). I am having a little trouble though, with a number of small issues, which I am finding hard to get answers through searches (and have spent a fair while searching). In navigating the tree, I want to be able to automatically expand nodes.
    Firstly, I want the Root node to automatically be expanded. I cannot see ways of doing this. I have seen references to EXPANDED being set for the JTree constructor, but I cannot see any reference in the 1.6 API for this.
    Secondly, I want to be able to expand or hide the contents of nodes through other means than clicking on the icon to the left of a non-leaf-node. For example a button that would hide the contents of (i.e. close) the currently selected node. Code such as:
    myNode.setExpanded(true);
    myNode.setExpanded(false);and
    myNode.isExpanded();

    That's the ticket - again something I had seen, but had been using in the wrong way, but your suggestion has helped me get it right. I was trying to expand the path before any more nodes were added to the root node. Then nodes are added, and the application loaded with the root node collapsed. So now I have placed the call at the end of the recursive call to populate the tree.
    Thanks again.

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

  • Saving expanded paths

    I've noticed that JTree keeps the expanded paths in some kind of cache. For example, if you expand a bunch of nodes under a certain parent, then collapse this parent and re-expand it again, all the previous expanded paths under this parent show up expanded again.
    This means JTree (or maybe each node) keeps a memory of its expanded state. Is there a way to retrieve all the expanded paths at once? What I would like to do is have my application save these expanded paths (we have to deal with very large trees) to restore them later (for example when the user reloads the application.
    Thanks for you thoughts :)

    I know that...
    My question is more, I want to make an algorythm that saves ALL paths that are expanded, so that I can later re-open the same paths when my application opens up again (after it was closed). What's the best way to do this?
    My idea was :
    -Put a tree expansion listener on my tree
    -In this listener, when the path is expanded save it in some kind of list or Set. This will be a path of tree nodes, so I'll have to retrieve the path of my objects instead.
    -Before my application closes, I save this path in some kind of user preferences (in file or in a datastore).
    -When my application re-opens, at the time I build my tree, I need to replace my path of objects with their respective path of nodes.
    -Then for each path of nodes, call the method
    makeVisible(path) of JTree.

  • JTree, branch expanding and TreeWillExpandEvent

    You can expand a branch in JTree component either by double clicking the node's name or by single clicking the branch expanding icon (next to node icon). How can I determine which way was used when receiving the TreeWillExpandEvent ? It seem that it does not provide this information

    It looks to me like TreeWillExpandEvent does not retain the mouse click information from the underlying event that caused the expansion. Looks like you would need to provide a custom UI and event mechanism to propagate that information.
    Mitch Goldstein

Maybe you are looking for

  • How do I create a bootable Snow Leopard partition on my iMac running Lion?

    Hi. I have recently bought an iMac running Lion.  I also have software such as Office 2004 and CS2 which I believe I can run using Rosetta, however I think I need Snow Leopard for this.  If I purchase Snow Leopard from the Online Store, how do I inst

  • Set range selection on a clip using "X" not working!

    So I just downloaded FCPX this afternoon and am trying to select a range on a clip in the Event Browser to then drag that selection down to the Timeline.  On a 20 second clip, I press the "I" at 7 seconds in, then I press "O" at 14 seconds.  That's t

  • Transfering MP3 library from Media Player to itunes music came but not art

    I transfered about 30mb of mp3 encoded music from my Media Player library to iTunes. The software said it was reading the artwork but nothing appears in iTunes. Is there something else to do beyond letting iTunes read the library?

  • Standby ORA-1110

    I had an error today identified from alert log the below: Errors in file /apps/oracle/admin/XPSPERS/bdump/xpsper_mrp0_19602.trc: ORA-01110: data file 181: '/oradata1/XPS_DATA/XPSPERS/D1_223YMD4_081100305804_0.dbf' ORA-00372: file 181 cannot be modifi

  • Redirecting from an abstract portal component

    Hi, I'm trying to redirect from an abstract portal component to a quicklink. I do it like told in this thread: Redirecting to external website from abstract portal component? private void redirectUrl(String target, IPortalComponentRequest request) {