Expansion of Jtree

in my application with its UI on swing i am trying to expand tree using expandPath() method of JTree but its not working.. basically expansion method is called when screen is refreshed to bring selection to previous selected node..
another thing to note is that expandRow() method is working and tree remain is expanded after calling this method unlike in above..
kindly suggest what could be probable source of error.

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

Similar Messages

  • Hide the expansion icon on a jtree.

    I need to hide the expansion icon (the "+") on a jtree.
    I tried to use DefaultTreeCellRenderer and the L&F options, but they hide all of the "+" icons of the tree. I need to hide the icons depending if the node has no-leaf icons.
    Thanx.
    pmadridb

    hi,
    you can change the property of common section view attribute. which is default in month. if u use input date component , i think you can overcome your problem..

  • JTree shows expansion icon when node hasn't got children

    When first displayed, my JTree shows the expansion icon next to non-leaf nodes that do not have children.
    If I click on one of the expansion icon it disappears.
    How can I stop it displaying this in the first place.
    i.e. only display it when the node does have children.
    Thanks.

    I've had a look at the source code to see why this is happening
    javax.swing.plaf.basic.BasicTreeUI.paintExpandControl( ... )
    seems to be the source of this effect.
    It seems that in deciding whether to display expansion icons or not, it ignores whether or not a node has children up until the node is expanded for the first time.
    Surely it should consider whether there are children or not from the beginning.
    Is this a bug or is there reasoning behind this? If so what? Is there any workaround.

  • JTree in Full  Expansion State????

    I am using JTree in one of my GUI Dialogs. It has several branches and leaves under the root.Whenever the JTree is displayed as of now only the root node is visible which shows root handles to expand and collapse the node. But i want the JTree to be in its full expansion state initially when the GUI is launched.i want all the root, branches and leafs to be displayed. How do i achieve this.Help on this is highly appreciated..
    Thanks much in advance..

    I have a pair of actions used to expand and collapse a given tree. I usually add them both to a toolbar and add that to the panel containing the tree. It seems to work.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class JTreeActions{
         JTree tree;
         String name;
         ExpandAllAction expand;
         CloseAllAction close;
         public JTreeActions(JTree treeIn, String nameIn){
              tree = treeIn;
              name = nameIn;
              expand = new ExpandAllAction(tree, "expand "+name);
              close = new CloseAllAction(tree, "close "+name);
         }//end of constructor method
         public JMenu getJMenu(){
              JMenu menu = new JMenu(name);
              menu.add(expand);
              menu.add(close);
              return menu;
         public JToolBar getJToolBar(){
              JToolBar toolBar = new JToolBar();
              //toolBar.add(new JLabel(" "+name+" "));
              toolBar.add(expand);
              toolBar.add(close);
              return toolBar;
    //inner classes
         * Expands all nodes of the supplied JTree or its subclasses
         * This action class extends AbstractAction
         * This can be added to menus and toolbars etc
         class ExpandAllAction extends AbstractAction{
              JTree tree;
              public ExpandAllAction(JTree treeIn, String name){
                   //provide some text
                   super(name);
                   this.tree = treeIn;
              public void actionPerformed(ActionEvent ev){
                   for (int i = 0; i < tree.getRowCount(); i++)
                        tree.expandRow(i);
         }//end of inner class
         * This action class extends AbstractAction
         * This can be added to menus and toolbars etc
         class CloseAllAction extends AbstractAction{
              JTree tree;
              public CloseAllAction(JTree treeIn, String name){
                   //provide some text
                   super(name);
                   this.tree = treeIn;
              public void actionPerformed(ActionEvent ev){
                   for (int i = tree.getRowCount(); i >= 0; i--)
                        tree.collapseRow(i);
         }//end of inner class
    //main method
         public static void main(String[] args){
              JTree tree = new JTree();
              JTreeActions tat = new JTreeActions(tree, "test tree");
             JFrame frame = new JFrame("Tree actions Test");
             frame.setDefaultCloseOperation( javax.swing.WindowConstants.DISPOSE_ON_CLOSE );
             frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent ev){
                        System.exit(0);
             frame.setBounds(0, 0, 750, 720);
             JPanel panel = new JPanel();
              frame.setContentPane(panel);
              panel.setLayout(new BorderLayout());
              frame.getContentPane().add(tat.getJToolBar(), BorderLayout.NORTH);
             frame.getContentPane().add(tree, BorderLayout.CENTER);
             JMenuBar menuBar = new JMenuBar();
             menuBar.add(tat.getJMenu());
             frame.setJMenuBar(menuBar);
             frame.show();
    }//end of class JTreeActions

  • How to load a directory in JTree with Children(On expansion)

    Hi,
    How can I load a Jtree directory with children on expanding the node of that directory.
    I have developed the following SSCCE. Please explain in its context.
    My specific question is, when you execute the code given here, you can see the file bb.1 inside the directory bb.
    bb.1 is a dummy which I used while creating the Jtree. When I expand bb, instead of the leaf bb.1 , I want to display some other file name, say qq.1 or jj.1.
    What should I do?
    Hope my question is clear(http://forums.sun.com/thread.jspa?threadID=5337544&start=20&tstart=0 -- please ignore the given link).
    //FileTreeFrame.java
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    public class FileTreeFrame extends JFrame {
      private JTree fileTree;
      private FileSystemModel fileSystemModel;
      public FileTreeFrame(String abc) {
        super("JTree FileSystem Viewer");
        // Build up your data
        List rootChildren = new ArrayList();
        rootChildren.add( new MyNode("aa") );
        List bbChildren = new ArrayList();
        bbChildren.add( new MyNode("bb.1") );
        rootChildren.add( new MyNode("bb", bbChildren) );
        rootChildren.add( new MyNode("cc") );
        MyNode rootNode = new MyNode("root", rootChildren);
        fileTree = new JTree(new FileSystemModel(new MyTreeNode(rootNode)));
        fileTree.setRootVisible(false);
        fileTree.setShowsRootHandles(true);
        getContentPane().add(fileTree);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(640, 480);
        setVisible(true);
      public static void main(String args[]) {
        new FileTreeFrame("");
    class FileSystemModel extends DefaultTreeModel {
        public FileSystemModel(DefaultMutableTreeNode node) {
              super(node);
        public boolean isLeaf(Object node) {
              MyTreeNode treeNode = (MyTreeNode)node;
              return !((MyNode)treeNode.getUserObject()).hasChildren();
    =======================================================
    //MyNode.java
    import java.util.List;
    public class MyNode {
          private String name;
          private List children;
          public MyNode(String name) {
                this.name = name;
          public MyNode(String name, List children) {
                this.name = name;
                this.children = children;
          public boolean hasChildren() {
                return children!=null && children.size()>0;
          public String toString() {
                return name;
          public List getChildren() {
                return children;
    =========================================================
    //MyTreeNode.java
    import java.util.Iterator;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class MyTreeNode extends DefaultMutableTreeNode {
        public MyTreeNode(MyNode node) {
            super(node);
            addSubNodes();
        private void addSubNodes() {
              MyNode content = (MyNode)getUserObject();
              if (content!=null && content.hasChildren()) {
                    for (Iterator it = content.getChildren().iterator(); it.hasNext();) {
                          add( new MyTreeNode((MyNode)it.next()) );
    }

    I believe JFileChooser has a method setFileSelectionMode() which will allow you to do this. You can configure the chooser to allow selection of FILES_ONLY, DIRECTORIES_ONLY or FILES_AND_DIRECTORIES.
    I have not used this myself but understand it will achieve what you need.

  • Non-leafNode in a JTree to be loaded on expansion

    I have a non-leaf DefaultMutableTreeNode going into a JTree, that I want to "load on demand" when the user expands it, with a TreeWillExpandListener.
    I've done "load-on-demand" nodes before, and I think the way I did it before involved having a dummy leaf node pre-loaded into the node. But is there a more elegant way to do it, without having to define a new node class?

    It worked for me .. Iam able to get the spaces ..
    type_20_record1+0(1) = type_20_record-rec_id.
    type_20_record1+1(1) = type_20_record-rec_type.
    type_20_record1+2(17) = type_20_record-work_num.
    type_20_record1+19(35) = type_20_record-surname.
    type_20_record1+54(7) = type_20_record-init_one.
    type_20_record1+61(7) = type_20_record-init_two.
    type_20_record1+68(1) = type_20_record-director.
    type_20_record1+69(9) = type_20_record-ni_num.
    type_20_record1+78(8) = type_20_record-gbdat.
    type_20_record1+86(1) = type_20_record-gesch.
    TRANSFER type_20_record1 TO file_name LENGTH 87.

  • JTree Path expansion help

    Hi,
    I have made my own jtree to load all the directories in the c drive. I am making a simple windows type browser. I allow users to select a driectory and create a new directory within it. The thing is, once this new directory is created it doesnt show up so i reinitialize the JTree to load all the directories again, and this time the new directory shows up in the directory it was created in. The problem is that before i reinitialize the tree again, i save a treepath for the directory the user is creating a new directory in., but after i reinitialize the tree i need to expand back to that path, i try using expandPath(savedTreePath) but its not working. Any ideas? Code is below.
    private class NewFolderListener implements ActionListener {
              public void actionPerformed(ActionEvent evt) {
                   DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
                             .getLastSelectedPathComponent();
                   if (selectedNode == null) {
                        System.out.println("New folder not created");
                        return;
                   File temp = (File) selectedNode.getUserObject();
                   String newFolderPath = temp.getAbsolutePath() + "\\" + "New Folder";
                   System.out.println(temp);
                   temp = new File(newFolderPath);
                   temp.mkdir();
                            TreePath tp = new TreePath(selectedNode.getPath);
                   makeTree();
                             tree.expandPath(tp);
    //Reinitialize tree method
    private void makeTree() {
              try {
                   //setLook();
                   tree = new SimpleTree("C:\\");
                   //location.setText("C:\\");
                   splitPane.setLeftComponent(new JScrollPane(tree));
                   tree.addTreeSelectionListener(new TreeSelectionListener() {
                       public void valueChanged(TreeSelectionEvent e) {
                           DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                                              tree.getLastSelectedPathComponent();
                           if(node!=null){
                                MyFile mf = (MyFile)node.getUserObject();
                                location.setText(mf.getAbsolutePath());     
                                fselected = mf;
                           makeRightPane();
                   tree.setExpandsSelectedPaths(true);
                   //cp.validate();
              } catch (Exception e) {
         }Anyone have any idea what i am doing wrong?

    Well ive tried using the tree model, calling methods
    such as reload() reload(node) , but none of the
    reloaded the new directory which was created for the
    node.The reload() method is only useful when you have modified existing nodes.
    Use other methods defined in DefaultTreeModel to change tree structure.

  • JTree expansion problem.

    Hey everybody,
    I have the following line of code:
    bookTree.expandPath(new TreePath(tempNode.getPath()));
    Where bookTree is a JTree and tempNode is a DefaultMutableTreeNode that was just plucked from the tree. The tree fails to expand. Does anyone know why? Any help would be greatly appreciated.
    thanks to all,
    dosteov

    I'll answer my own question, it should be:
    bookTree.expandPath(new TreePath(tempNode.setSelectionPath()));
    This will open the tree to the specified node and select it. Does anyone know what exactly expandPath does? Does the node need to have children to expand or something.
    dosteov

  • Noob question: jtree expansion

    hello all,
    i have a jtree loading from the database with customized nodes. tree is loaded and displays nicely the root node and the first level:
    //what i have
    root
    level1a
    level1b
    level1c
    //what i want
    root
    level1a
    level2a
    level2b
    level2c
    level1b
    level2a
    level2b
    level1c
    level2a
    i need one more level to show and ive tried the expandrow in a loop but calling this for each row (level1) doesnt work, it only expands one of the level1 nodes no matter how many times you call it.
    expandEntireTree is not an option...
    my guess is that i have to do somesort of getpath for each of these but im such a noob to swing i cant seem to get a grip on the methods i need... any help?
    Thanks,
    txjump

    d'oh
    //what i have
    root
        level1a
        level1b
        level1c
    //what i want
    root
        level1a
            level2a
            level2b
            level2c
        level1b
            level2a
            level2b
        level1c
            level2asorry!
    no replies? is this an incredibly stoopid thing to ask or do people just not do this? or.. ?
    Message was edited by: txjump
    txjump

  • How to expand a JTree depending on a property

    Hi I have a JTree that needs to be expandAll if a property in the ini file is true. Can some tell me how I can do it or give me an example. If needed i can post my code. Here the addtreeDisplays() has to expandAll depending on a string(true ).
    Can some help me out.
    Thanks,
    public class TreeDisplayPanel extends JPanel implements QMRequestListener,
                                                            TopologySelectionListener,
                                                                          PropertyChangeListener
        /** Creates new TreeDisplayPanel */
        //Key to get from property file
        String _treeKey = "tree.display.type";
        //default display
        public final static int TREE_DISPLAY = 0;
        public final static int STAR_DISPLAY = 1;
        public final static int BOTH_DISPLAY =2;
         Properties _displayProp = null;
        //Main panel where everything gets put on to be displayed
        public JPanel _mainDisplayPanel;
        //current default display
        private int treeDisplayPreference = STAR_DISPLAY;
        private MQETabbedPane _treeTabPane;
        private MQETabbedPane _viewTabPane;
        private String treeDisplayTitle;
         static private final String treeviewKey = "tree.view.text";
         static private final String starviewKey = "star.view.text";
         static private final String splitviewKey = "split.view.text";
         static private final String mergeviewKey = "merge.view.text";
         // Default tree displays.
         private HyperbolicTreePanel hyperbolicTreePanel = null;
         private NavigatorTreePanel navigatorTreePanel = null;
         // A store for any queue manager tree displays created
         // by the user. This will enable these trees to be
         // modified whenever the user invokes a expand/collapse
         // all action on a node or whenever the user changes
         // the leaf node expansion preference.
         private Vector<NavigatorTreePanel> qmgrTreeDisplays =
            new Vector<NavigatorTreePanel>();
         //HashMap of indexes correspond to indexes in tabbed paned that are merged, it contains
        //hashtables of components in those merged indexes
        HashMap _qmMergedIndexes = new HashMap();
        //Current listeners to this panel on node selections
        protected Vector<TopologySelectionListener> _tsListeners =
            new Vector<TopologySelectionListener>();
         private TopologyModel m_model = null;
         private TopologyModelNode m_nnode = null;
         private TopologyDisplayPanel tdp = null;
        public TreeDisplayPanel(TopologyModel model, Properties prop, String displayTitle) {
            super(new BorderLayout());
              m_model = model;
              _displayProp = prop;
              treeDisplayTitle = displayTitle;
            initComponent();
            initGui();
        private void initComponent()
              _mainDisplayPanel = ComponentFactory.getInstance().createTitledPanel(treeDisplayTitle);
              _mainDisplayPanel.setLayout(new BorderLayout());
              add(_mainDisplayPanel, BorderLayout.CENTER);
        private void initGui()
            if (_displayProp != null)
                   // Get the current display preference.
                   String defaultDisplay = Integer.toString(STAR_DISPLAY);
                treeDisplayPreference = Integer.parseInt(_displayProp.getProperty(_treeKey, defaultDisplay));
            try
                //Add according to your display property
                _treeTabPane = new MQETabbedPane();
                _viewTabPane = new MQETabbedPane(JTabbedPane.BOTTOM);
                _viewTabPane.addMouseListener(new MouseListener()
                    public void mouseClicked(MouseEvent e)
                        final int tabNum = _viewTabPane.getUI().tabForCoordinate(_viewTabPane,e.getX(),e.getY());
                        //Only if the mouse click is a right mouse and tab number is not on overview pane or doc pane is the popup valid
                        if (SwingUtilities.isRightMouseButton(e) && tabNum > 1)
                            final String tabStr = _viewTabPane.getTitleAt(tabNum);
                            JPopupMenu popup = new JPopupMenu();
                            JMenuItem menuItem1 = new JMenuItem(new AbstractAction("Close " + tabStr)
                                public void actionPerformed(ActionEvent e)
                                    //Remove it from our HashMap of merged panes if it exists
                                    if (_qmMergedIndexes.containsKey(tabStr))
                                        _qmMergedIndexes.remove(tabStr);
                                            // Remove the Qmgr tree display.
                                            NavigatorTreePanel treePanel = (NavigatorTreePanel)_viewTabPane.getComponentAt(tabNum);
                                            ExpandingModelNode model = (ExpandingModelNode)treePanel.getNavigatorTreeModel();
                                            model.getNode().removeTreeModelListener(model);
                                            qmgrTreeDisplays.remove(treePanel);
                                    _viewTabPane.removeTabAt(tabNum);
                                  String mergeview = StringFactory.getString(mergeviewKey);
                            JMenu merge = new JMenu(mergeview);
                            merge.setEnabled(false);
                            int numTabs = _viewTabPane.getTabCount();
                            //System.out.println("Num of tabs " + numTabs);
                            //Only allow merging if you have more then 2 panes (1 - Overview, 2 - Qmgr, 3-Qmgr....
                            //Also if the current pane is not a merge pane already
                            if (numTabs > 3 && !_qmMergedIndexes.containsKey(tabStr))
                                //Do not enable this menu if the number of already merged Indexes - the number of tabs
                                //is greater then two (One Valid pane + Overview pane). The reason is because then there is
                                //no valid pane to merge with
                                if ((numTabs - _qmMergedIndexes.size()) > 3)
                                    merge.setEnabled(true);
                                    for (int i = 2; i<numTabs; i++)
                                        //Add only valid tabs and not already merged tabs
                                        if (i != tabNum && !_qmMergedIndexes.containsKey(_viewTabPane.getTitleAt(i)))
                                            //JMenuItem mergeItem = new JMenuItem(new AbstractAction(_viewTabPane.getTitleAt(i))
                                                      JMenuItem mergeItem = new JMenuItem(new AbstractAction(_viewTabPane.getToolTipTextAt(i))
                                                public void actionPerformed(ActionEvent e)
                                                    try
                                                        //System.out.println("Action Name for " + e.getActionCommand());
                                                        //Work around for java bug in JTabbedPane
                                                        _viewTabPane.setSelectedIndex(0);
                                                        _viewTabPane.validate();
                                                        //End workaround
                                                        //Strip off the fully qualified name to contain only the name of the QM name
                                                                     String mergeTabName = m_model.getQMgrName(e.getActionCommand());
                                                                     JPanel splitPanel = new JPanel(new BorderLayout());
                                                        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
                                                        splitPane.setBorder(null);
                                                        splitPane.setOneTouchExpandable(true);
                                                        int mergeTabIndex =  _viewTabPane.indexOfTab(mergeTabName);
                                                        String mergeTabString = _viewTabPane.getTitleAt(mergeTabIndex);
                                                                     Component mergeComp = _viewTabPane.getComponentAt(mergeTabIndex);
                                                        String mergeCompAddress = _viewTabPane.getToolTipTextAt(mergeTabIndex);
                                                                     splitPane.setLeftComponent(mergeComp);
                                                                     int currentTabIndex =  _viewTabPane.indexOfTab(tabStr);
                                                        Component currentComp = _viewTabPane.getComponentAt(currentTabIndex);
                                                                     String currentCompAddress = _viewTabPane.getToolTipTextAt(currentTabIndex);
                                                        splitPane.setRightComponent(currentComp);
                                                        splitPanel.add(splitPane, BorderLayout.CENTER);
                                                        String mergeName = mergeTabName + "/" + tabStr;
                                                                     String toolTipName = mergeCompAddress + " | " + currentCompAddress;
                                                        //_viewTabPane.addTab(mergeName, splitPanel);
                                                                     addTabToDisplay(mergeName, toolTipName, splitPanel);
                                                        splitPane.setDividerLocation(.5);
                                                        int mergeIndex = _viewTabPane.indexOfTab(mergeName);
                                                                      if (mergeIndex != -1)
                                                            //_viewTabPane.setToolTipTextAt(mergeIndex, mergeName);
                                                                          //_viewTabPane.setSelectedIndex(mergeIndex);
                                                            //Now lets update our ongoing vector/hashmap
                                                            //Create a hash map with the current merged view
                                                            Hashtable mergeViews = new Hashtable();
                                                            mergeViews.put(mergeCompAddress,mergeComp);
                                                            mergeViews.put(currentCompAddress,currentComp);
                                                            _qmMergedIndexes.put(mergeName, mergeViews);
                                                    catch (Exception ex)
                                                        ex.printStackTrace();
                                            merge.add(mergeItem);
                                  String splitKey = StringFactory.getString(splitviewKey);
                            JMenu splitMenu = new JMenu(splitKey);
                            splitMenu.setEnabled(false);
                            //Only allow to split if the current tab has a merged view
                            if (_qmMergedIndexes.containsKey(tabStr))
                                splitMenu.setEnabled(true);
                                Hashtable mergeHash = (Hashtable)_qmMergedIndexes.get(tabStr);
                                Enumeration enumeration = mergeHash.keys();
                                while (enumeration.hasMoreElements())
                                    //Create a new menu item for each QM in View
                                    String node = (String)enumeration.nextElement();
                                    JMenuItem mergeItem = new JMenuItem(new AbstractAction(node)
                                        public void actionPerformed(ActionEvent e)
                                            //Work around for java bug in JTabbedPane
                                            _viewTabPane.setSelectedIndex(0);
                                            _viewTabPane.validate();
                                            //End workaround
                                            String splitTabName = e.getActionCommand();
                                            //Get the merge hash for this tab num
                                            Hashtable splitHash = (Hashtable)_qmMergedIndexes.get(tabStr);
                                            Enumeration enumeration = splitHash.keys();
                                            _viewTabPane.removeTabAt(tabNum);
                                                      int iIndexOfSplit = 0;
                                            while (enumeration.hasMoreElements())
                                                //Add new pane for the views in the hashtable
                                                String nodeAddress = (String)enumeration.nextElement();
                                                           String nodeName = m_model.getQMgrName(nodeAddress);
                                                           NavigatorTreePanel currentComp = (NavigatorTreePanel)splitHash.get(nodeAddress);
                                                addTabToDisplay(nodeName,nodeAddress,currentComp);
                                                           //Now if this tab this we just added is equal to the menu item of the split menu,
                                                           //store this so that we can give focus to it later
                                                           if (splitTabName.equals(nodeAddress))
                                                                iIndexOfSplit = _viewTabPane.getTabCount()-1;
                                            //Also remove it from our vector of merged tabs
                                            _qmMergedIndexes.remove(tabStr);
                                            //int mergeIndex = _viewTabPane.indexOfTab(splitTabName);
                                            //if (mergeIndex != -1)
                                                      if (iIndexOfSplit != -1)
                                                //_viewTabPane.setSelectedIndex(mergeIndex);
                                                           _viewTabPane.setSelectedIndex(iIndexOfSplit);
                                    splitMenu.add(mergeItem);
                            popup.add(menuItem1);
                            popup.add(merge);
                            popup.add(splitMenu);
                            if (popup != null)
                                Point p = e.getPoint();
                                popup.show((Component)e.getSource(), (int)p.getX(), (int)p.getY());
                    public void mouseEntered(MouseEvent e)
                    public void mouseExited(MouseEvent e)
                    public void mousePressed(MouseEvent e)
                    public void mouseReleased(MouseEvent e)
                   //Don't forget to add the tree's
                   addTreeDisplays();
                _viewTabPane.addTab(StringFactory.getString("perspective.display.overview.tab"), _treeTabPane);
                   _viewTabPane.addTab(StringFactory.getString("perspective.display.documentation.tab"), new DocDisplayPanel());
                _mainDisplayPanel.add(_viewTabPane, BorderLayout.CENTER);
            catch(Exception e)
                e.printStackTrace();
         private void addTabToDisplay(String nameStr, String toolStr, JComponent c)
              if (_viewTabPane == null)
                   return;
              _viewTabPane.addTab(nameStr, c);
              int tabNum = _viewTabPane.getTabCount()-1;
              if (toolStr != null)
                   _viewTabPane.setToolTipTextAt(tabNum, toolStr);
              _viewTabPane.setSelectedIndex(tabNum);
         private void addTreeDisplays()
              String starKey = StringFactory.getString(starviewKey);
              String treeKey = StringFactory.getString(treeviewKey);
              //navigatorTreePanel.expandTreePath(this, true);
              String test = MQEPreferencesDialog.getPreferenceValue("expand.leaf.startup");
              System.out.println("test{{{{{{{{{{"+test);
              //System.out.println("test{{{{{{{{{{"+m_nnode.);
              if (treeDisplayPreference == BOTH_DISPLAY)
                   hyperbolicTreePanel = new HyperbolicTreePanel(m_model);
                   hyperbolicTreePanel.addQMRequestListener(this);
                   hyperbolicTreePanel.addTopologySelectionListener(this);
                   //hyperbolicTreePanel.expandTreePath((TopologyModelNode)m_model.getRoot(), true);
                   //hyperbolicTreePanel.expandTreePath(m_nnode, true);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("staricon"), hyperbolicTreePanel, starKey);
                   navigatorTreePanel = new NavigatorTreePanel(m_model);
                   navigatorTreePanel.addQMRequestListener(this);
                   navigatorTreePanel.addTopologySelectionListener(this);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("treeicon"), navigatorTreePanel, treeKey);
              else if (treeDisplayPreference == TREE_DISPLAY)
                   navigatorTreePanel = new NavigatorTreePanel(m_model);
                   navigatorTreePanel.addQMRequestListener(this);
                   navigatorTreePanel.addTopologySelectionListener(this);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("treeicon"), navigatorTreePanel, treeKey);
              else
                   hyperbolicTreePanel = new HyperbolicTreePanel(m_model);
                   hyperbolicTreePanel.addQMRequestListener(this);
                   hyperbolicTreePanel.addTopologySelectionListener(this);
                   _treeTabPane.addTab("", IconFactory.getInstance().getIcon("staricon"), hyperbolicTreePanel, starKey);
        public void addTopologySelectionListener(TopologySelectionListener tsl)
            if (tsl != null)
                _tsListeners.add(tsl);
        public void removeTopologySelectionListener(TopologySelectionListener tsl)
            if (tsl != null)
                _tsListeners.remove(tsl);
        protected void fireTopologySelection(TopologyModelNode node)
            for (TopologySelectionListener tsl : _tsListeners)
                tsl.receiveTopologySelection(node);
       /* TopologySelectionListener methods                                     */
        public void receiveTopologySelection(TopologyModelNode node)
            //Since this panel can have multiple panels in it's current Tabbed display.
            //This class registers to each of the TopologyDisplayPanels as a listener for selections
            //This way no matter who is currently active, they will funnel the event to here and it this
            //panel will send the event on foward
            if (node != null)
                fireTopologySelection(node);
       /* QMRequestListener methods                                             */
        public void receiveQMRequest(TopologyModelNode node)
            //Check to see if this node is already in a Tab already
            System.out.println("Queue Manager request");
              boolean doesExist = false;
            int tabNum =0;
              //Fix for activity 00033248 TAB PANES FOR IDENTICAL QMANAGERS ON DIFF MACHINES
              //The only unique names are in the tooltips so lets just cycle through all the tabs
              //and search for this Queue Manager name.  Using indexOfTab in JTabbedPane will not
              //work here because it will return first location of a matching queue manager name, but
              //we could have multiple tabs open with same queue manager name.
              for (int i = 0; i < _viewTabPane.getTabCount();i++)
                   String toolTipStr = _viewTabPane.getToolTipTextAt(i);
                   //Using the string method for indexOf, covers us when we have a merged tab window
                   if ((toolTipStr != null) && (toolTipStr.indexOf(((ResourceProxy)node).getAddress().trim()) != -1))
                        //We already have existing queue manager tab open
                        doesExist = true;
                        tabNum = i;
                        break;
              if ( !doesExist)
                   //Create the tab
                NavigatorTreePanel treePanel = new NavigatorTreePanel(new ExpandingModelNode(node));
                treePanel.addTopologySelectionListener(this);
                   // Add the tree panel to a container so that it can be accessed
                   // for expand/collapse all and tree refresh actions.
                   qmgrTreeDisplays.add(treePanel);
                   //Fix for activity 00033248 TAB PANES FOR IDENTICAL QMANAGERS ON DIFF MACHINES
                   addTabToDisplay(((ResourceProxy)node).getName().trim(), ((ResourceProxy)node).getAddress().trim(), treePanel);
                node.getModel().expandNode(node);
              else
                   _viewTabPane.setSelectedIndex(tabNum);
       /* PropertyChangeListener methods                                        */
            public void propertyChange(PropertyChangeEvent evt){
              String propertyChanged = evt.getPropertyName();
              if (propertyChanged.equals(MQEDisplayPreferences.treeDisplayProperty)){
                   int newPreference = ((Integer)evt.getNewValue()).intValue();
                   changeTreeDisplays(newPreference);
              else if (propertyChanged.equals(MQEDisplayPreferences.expandLeafProperty)){
                   // The enable leaf node preference has changed so update the MQE
                   // tree displays according to the new preference setting.
                   refreshTreeDisplays();
              else{
                   // Ignore the property change event.
        * Changes the trees displayed by MQE according to
         * the preference set by the current user.
        * @param the new trees display preference.*/
         public void changeTreeDisplays(int preference)
              // Assign the new tree display preference.
              treeDisplayPreference = preference;
              // Recreate the tree display according
              // to the new preference.
              m_model.removeTreeModelListeners();
              _treeTabPane.removeAll();
              addTreeDisplays();
              refreshTreeDisplays();
        * Fully expands the Navigator display trees from the specified node.
        * @param the node from which each tree will be fully expanded.
         public void expandAll(TopologyModelNode node)
              node.expandAll();
              final TopologyModelNode fnode = node;
              Runnable doTask = new Runnable(){
                   public void run(){
                        // Fire a tree structure changed notification for
                        // the StarTree, (1) because it will not display
                        // tree nodes correctly without it and (2) it appears
                        // to be the only tree interested in doing anything
                        // with it!
                        fnode.fireTreeStructureChanged(TopologyModel.STRUCTURE_CHANGE);
                        if (hyperbolicTreePanel != null)
                             hyperbolicTreePanel.expand(fnode);
                        if (navigatorTreePanel != null)
                             navigatorTreePanel.expand(fnode);
                        for (NavigatorTreePanel navTreePanel : qmgrTreeDisplays){
                             navTreePanel.expand(fnode);
              SwingUtilities.invokeLater(doTask);
        * Fully collapses the Navigator display trees from the specified node.
        * @param the node from which each tree will be fully collapsed.
         public void collapseAll(TopologyModelNode node)
              final TopologyModelNode fnode = node;
              Runnable doTask = new Runnable(){
                   public void run(){
                        if (hyperbolicTreePanel != null)
                             hyperbolicTreePanel.collapse(fnode);
                        if (navigatorTreePanel != null)
                             navigatorTreePanel.collapse(fnode);
                        for (NavigatorTreePanel navTreePanel : qmgrTreeDisplays){
                             navTreePanel.collapse(fnode);
              SwingUtilities.invokeLater(doTask);
        * Will ensure that all tree nodes, starting from the root, are correctly displayed.
         public void refreshTreeDisplays()
              if (hyperbolicTreePanel != null){
                   TopologyModel model = hyperbolicTreePanel.getTopologyModel();
                   if (model != null){
                        hyperbolicTreePanel.expandTreePath((TopologyModelNode)model.getRoot(), true);
                        hyperbolicTreePanel.refreshTreeDisplay((TopologyModelNode)model.getRoot());
              if (navigatorTreePanel != null){
                   TopologyModel model = navigatorTreePanel.getTopologyModel();
                   if (model != null){
                        navigatorTreePanel.refreshTreeDisplay((TopologyModelNode)model.getRoot());
                        navigatorTreePanel.repaint();
              for (NavigatorTreePanel navTreePanel : qmgrTreeDisplays){
                   ExpandingModelNode model = (ExpandingModelNode)navTreePanel.getNavigatorTreeModel();
                   if (model != null){
                        navigatorTreePanel.expand((TopologyModelNode)model.getRoot());
                        navTreePanel.refreshTreeDisplay((TopologyModelNode)model.getRoot());
                        navTreePanel.repaint();
    }

    you really don't need to post all that code, few people will read it, or try to compile/run it.
    just a tree in a scrollpane in a frame is all you need, then add the method/problem to the basic,
    and post that so its only 20 to 30 lines long.
    here's your basic tree/scrollpane/frame, with an expandAll()
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        JTree tree = new JTree();
        expandAll(tree);
        JFrame f = new JFrame();
        f.getContentPane().add(new JScrollPane(tree));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public void expandAll(JTree tree)
        int row = 0;
        while (row < tree.getRowCount())
          tree.expandRow(row);
          row++;
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }so, is your problem with the expandAll(), or with reading the properties file?

  • What's a good way to show attributes in a JTree made from DOM?

    I'm doing a pretty simple project that's basically just taking an XML document, making a DOM out of it, and then I want to represent the document in a JTree. The code I have now works swimmingly, except it doesn't do anything about attributes. Ideally (for the purposes of the tree), I'd like the attributes to show up as children of the node of which they are an attribute, and then each attribute node would itself have a child representing the value.
    basically I want to go from this:
    <xmlNode attribute=value>
       <child>
       </child>
    </xmlNode>To a JTree like this ('v' being the expansion arrow on the tree):
    v xmlNode
       v attribute
          v value
       v childI realize they're not of equivalent meaning, but for my purposes representing the true structure of the XML is not as important as meaningfully representing the information it contains.
    My question is basically, is there a more straightforward way to accomplish this than to manually add children nodes for all of the attributes? How would you approach this problem? I'm not looking for code or for someone to give me the "answer," I just wanted to get a second opinion.

    camickr and DrClap, thanks for your ideas! Both of those solutions seem pretty reasonable for what I'm doing, I'll experiment with them (I do indeed already have a custom Tree model, so adding this in wouldn't actually be too difficult... I don't know why that didn't occur to me!).
    Thanks for the replies!

  • Making a node in JTree non expandable

    How do I make a node in a JTree non expandable. The nodes in the tree are DefaultMutableTreeNode. I have a tree with root R. It has children ch1, ch2, ch3. Nodes ch1 etc also have X number of children. What I want is if I click (either double click on the node or single clicking on the '+') on either of the child nodes ch1, ch2 and ch3 to disable expansion i.e. stop the tree collapsing beyond those nodes. I have tried tree.setExpandsSelectedPaths(false) and others but it still doesnt work. Any help much appreciated. Thanx.

    Thanx Jeanette, that is exactly!! what I'm looking for. Much appreciated.

  • 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

  • JTree custom implementation

    Hi All,
    I have application, which eats all the memory, when I load big structure in JTree.
    So I have modified following function
    DefaultTreeMutableNode {
    public void insert(MutableTreeNode newChild, int childIndex) {
              children = new Vector();
    As follow:
    DefaultTreeMutableNode {
    public void insert(MutableTreeNode newChild, int childIndex) {
              children = new ArrayList(1);
    As my jTree usually has single nodes. And Default constructor of Vector() creates array of 10 child nodes, for each node.
    But still it uses the same memory ???
    Is there any way to reduce memory usage by JTree nodes, so it can handle big strucutre.
    Is there any custom implemenation is avaliable.
    Thank you for your time.
    Avin Patel

    I guess ur application is a perfect candidate for a MVC implementation. In the tree there are 2 ways to do that. u can either write ur own TreeModel or u can write ur ur own TreeNode. I can help u write either of the two.
    I can give u working examples from my application in each of them. U can also make the creation of the child nodes dyanamic and on a "on-demand-basis", by creating them only on the expansion of the parent nodes, as mentioned above.
    The first way to do that is to override the implementation of the DefaultTreeModel class:
    Plz find below an implementaion of the same:
    public class GrpModuleTreeModel extends DefaultTreeModel
         TerminationPointsModel mModel = null;
         TreePanel mTreePanel;
         GrpModuleTreeModel(TerminationPointsModel model,TreePanel treePanel)
              super(null);
              mModel = model;
              mTreePanel=treePanel;
         public int getIndexOfChild(Object parent, Object child)
              if (parent.equals(mTreePanel.mParent.getParentFrame().getNEName()))
                   ArrayList rackList = new ArrayList(mModel.getRacks());
                   return rackList.indexOf(child);
              if (parent instanceof Rack)
    //               return mModel.getSubracks(parent).size();
                   ArrayList subrackList = new ArrayList(((Rack)parent).getSubracks());
                   return subrackList.indexOf(child);
              if (parent instanceof Subrack)
    //               return mModel.getModules(parent).size();
                   ArrayList moduleList = new ArrayList(((Subrack)parent).getModules());
                   return moduleList.indexOf(child);
              if (parent instanceof Module)
    //               return this.mModel.getTerminationPoints(parent).size();
                   ArrayList tpList = new ArrayList(((Module)parent).getTerminationPoints());
                   return tpList.indexOf(child);
              if (parent instanceof TerminationPointA)
    //               return this.mModel.getTerminationPoints(parent).size();
                   ArrayList tpList = new ArrayList(((TerminationPointA)parent).getTerminationPointList());
                   return tpList.indexOf(child);
              return -1;
         public boolean isLeaf(Object node)
              if (node instanceof TerminationPointA )
                   if (node instanceof NonConfigurableCrossConnection ) return true;
                   return (((TerminationPointA)node).getTerminationPointList()==null)? true: false;
    //               java.util.ArrayList list=((TerminationPointA)node).getTerminationPointList();
    //               System.out.println("Type====== "+((TerminationPointA)node).getTerminationPointType()+","+list);
    //               if (list!=null)
    //                    System.out.println("Number of nodes ========= "+list.size());
    //                    for (int i = 0; i < list.size(); i++)
    //                         System.out.println(list.get(i).getClass().getName());
    //               return true;
              if (node instanceof Rack)
                   return (((Rack)node).getSubracks()==null)? true: false;
              if (node instanceof Subrack)
                   return (((Subrack)node).getModules()==null)? true: false;
              if (node instanceof Module)
                   return (((Module)node).getTerminationPoints()==null)? true: false;
              return false;
         public Object getChild(Object parent, int index)
              if (parent.equals(mTreePanel.mParent.getParentFrame().getNEName()))
                   ArrayList rackList = new ArrayList(mModel.getRacks());
                   return (rackList!=null)? rackList.get(index):null;
              if (parent instanceof Rack)
    //               return mModel.getSubracks(parent).size();
                   ArrayList subrackList = new ArrayList(((Rack)parent).getSubracks());
                   return (subrackList!=null? subrackList.get(index):null);
              if (parent instanceof Subrack)
    //               return mModel.getModules(parent).size();
                   ArrayList moduleList = new ArrayList(((Subrack)parent).getModules());
                   return moduleList!=null? moduleList.get(index):null;
              if (parent instanceof Module)
    //               return this.mModel.getTerminationPoints(parent).size();
                   ArrayList tpList = new ArrayList(((Module)parent).getTerminationPoints());
                   return tpList!=null? tpList.get(index):null;
              if (parent instanceof TerminationPointA)
    //               return this.mModel.getTerminationPoints(parent).size();
                   ArrayList tpList = new ArrayList(((TerminationPointA)parent).getTerminationPointList());
                   return tpList.get(index);
              return null;
         public int getChildCount(Object parent)
              if (parent ==null)
                   return -1;
              if (parent.equals(mTreePanel.mParent.getParentFrame().getNEName()))
                   return mModel.getRacks()!=null ? mModel.getRacks().size() : -1;
              if (parent instanceof Rack)
    //               return mModel.getSubracks(parent).size();
                   return ((Rack)parent).getSubracks()!=null ? ((Rack)parent).getSubracks().size() : -1;
              if (parent instanceof Subrack)
    //               return mModel.getModules(parent).size();
                   return ((Subrack)parent).getModules()!= null? ((Subrack)parent).getModules().size() : -1;
              if (parent instanceof Module)
    //               return this.mModel.getTerminationPoints(parent).size();
                   return ((Module)parent).getTerminationPoints() != null ? ((Module)parent).getTerminationPoints().size(): -1;
              if (parent instanceof TerminationPointA)
    //               return this.mModel.getTerminationPoints(parent).size();
                   return ((TerminationPointA)parent).getTerminationPointList()!= null ? ((TerminationPointA)parent).getTerminationPointList().size(): -1;
              return -1;
         public Object getRoot()
              return mTreePanel.mParent.getParentFrame().getNEName();
    IF this does'nt suffice then I can tell u another way by which u can create ur own TreeNode.
    BR
    Mohit

  • JTree - changed content, refresh

    Hello,
    I have a problem in my program I can`t solve...
    basically I am using drop-down menu with different drives (c:, d:, etc.). Don`t ask me why I don`t use the JTree to display all the drives, I simply need to display each drive separately.
    when I select the drive, JTree pops up with the content of the drive.
    Problem comes in, when the JTree is already displayed and I go into my drop-down menu to select a different drive.... Everything seems to work fine in background.... The tree gets build up, I just somehow cannot update (or refresh) the screen....
    did anyone experienced similar problem?
    thank you
    Otakar

    No, I am not using TreeModel.. Let me post the code... I am using 3 different files:
    MainModule.java
    DetectDrives.java
    FileSystem.java
    I think You might wanna see the ChoiceListener in MainModule
    thank you for you time
    MainModule.java
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.awt.*;
    import java.awt.event.*;
    public class MainModule{
         private JFrame aFrame;         // BASE frame
         private JPanel driveListPane;
         private JList  driveList;
         // MENU Bar Components
         private JMenuBar aMenuBar;
         private JMenu fileMenu, editMenu, viewMenu, settingsMenu, helpMenu;
         private JMenuItem newMenuItem, openMenuItem, saveMenuItem,                // FILE menu Items
                                           saveAsMenuItem, exitMenuItem,                     //
                                           selectDriveMenuItem, selectOutputMenuItem;        // SETTINGS menu Items
          // ComboBox
         private JComboBox aComboBox;
          // Buttons
         private JButton selectDriveButton, printButton;
         // Listeners
         private PrintButtonListener prtListener;
         private ChoiceListener choiceListener;
         // Labels
         private JLabel sourceLabel, label1, label2;
         private int listRows;
         public static String drive;
         private DetectDrives dd;
         private FileSystem fs;
         private int ct;
         /*============ CONSTRUCTOR ===========================================================\
         |
         public MainModule(){
             ct = 0;
              // create a MAIN WINDOW (Frame)
              drive = new String("C:\\");
              aFrame = new JFrame("Otax Drive Printer 0.99b");
              aFrame.setSize(800, 600);
              aFrame.setLocation(100, 50);
              aFrame.getContentPane().setLayout(null);
              aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // create the categories in a menu bar
              aMenuBar = new JMenuBar();
              fileMenu = new JMenu("File");
              editMenu = new JMenu("Edit");
              viewMenu = new JMenu("View");
              settingsMenu = new JMenu("Settings");
              helpMenu = new JMenu("Help");
              // create menu items for FILE menu
              newMenuItem = new JMenuItem("New", 'N');
              openMenuItem = new JMenuItem( "Open", 'O');
              saveMenuItem = new JMenuItem( "Save", 'S' );
                     saveAsMenuItem = new JMenuItem( "Save As", 'A');
                     exitMenuItem = new JMenuItem("Exit", 'E');
              // create menu items for SETTINGS menu
                     selectDriveMenuItem = new JMenuItem("Select Drive", 'D');
                     selectOutputMenuItem = new JMenuItem("Select Output", 'O');
              // detect drives mounted to system and put them into JComboBox
              dd = new DetectDrives();
              aComboBox = new JComboBox(dd.detectCdDrives());
              aComboBox.setBounds(100, 5, 180, 20);
              //create labels
              sourceLabel = new JLabel("Select Source:");
              sourceLabel.setBounds(6, 4, 90, 20);
                     label1 = new JLabel("Current Drive: ");
              label1.setBounds(2, 500, 90, 20);
              label2 = new JLabel();
              label2.setBounds(85, 500, 50, 20);
              //create buttons
              printButton = new JButton("Print");
              printButton.setBounds(2, 50, 101, 16);
                     //create Accelerators for FILE MenuItems
                     newMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_N, InputEvent.CTRL_MASK, false));
              saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                   KeyEvent.VK_S, InputEvent.CTRL_MASK, false));
              //create the action listeners (listener definitions bellow)
              prtListener = new PrintButtonListener();
              choiceListener = new ChoiceListener();
              //connect the action listeners with menu items
              printButton.addActionListener(prtListener);
              aComboBox.addActionListener(choiceListener);
         // LISTENERS Definitions start HERE ====================================
         public class PrintButtonListener implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   System.out.println("print action performed: " + drive);
         public class ChoiceListener implements ActionListener{
             public void actionPerformed( ActionEvent e)
                  ct++;
                  System.out.println(ct + " event started");
               String drive = new String(aComboBox.getSelectedItem().toString().substring(0,2));
               label2.setText(drive);
               fs = new FileSystem(drive + "//");
               fs.sortFiles();
               fs.addNodes(drive);
               DefaultMutableTreeNode top = fs.getNodes();
               JTree tree = new JTree(top);
               tree.setBounds(10, 30, 500, 450);
                  aFrame.getContentPane().add(tree);
               aFrame.repaint();
         public void addComponents(){
              aMenuBar.add(fileMenu);        // create menu
              aMenuBar.add(editMenu);
              aMenuBar.add(settingsMenu);
              aMenuBar.add(helpMenu);
              fileMenu.add(newMenuItem);     //add items to the FILE menu
              fileMenu.add(openMenuItem);
              fileMenu.addSeparator();
              fileMenu.add(saveMenuItem);
                     fileMenu.add(saveAsMenuItem);
                     fileMenu.addSeparator();
                     fileMenu.add(exitMenuItem);
              settingsMenu.add(selectDriveMenuItem);
              settingsMenu.add(selectOutputMenuItem);
              aFrame.setJMenuBar(aMenuBar);
              aFrame.getContentPane().add(aComboBox);
              aFrame.getContentPane().add(sourceLabel);
              aFrame.getContentPane().add(label1);
              aFrame.getContentPane().add(label2);
              aFrame.setVisible(true);
         public static void main(String [] args){
              MainModule m1 = new MainModule();
              m1.addComponents();
    DetectDrives.java
    import java.io.*;
    import java.util.Vector;
    import javax.swing.filechooser.*;
    public class DetectDrives{
         private FileSystemView fsv;
         private File[] roots;
         private Vector drives;
         /*======== CONSTRUCTOR =====================================================================\
         |Purpose: To INITIALIZE the object                                                          |
         |Variables: (FileSystemView) fsv - creates the Object containing info about current system  |
         |           (File[]) roots - array used to store all drives currently mounted to system     |
         |           (Vector) drives - vector used for storage of selected info about drives         |
           \==========================================================================================*/
         public DetectDrives(){
              drives = new Vector(0,1); // *Create empty Vector(0) with expansion capacity (1)
              //--- Get a FileSystemView object for the current system
             fsv = FileSystemView.getFileSystemView();
            //--- Get an array of File objects describing the 'roots' attached to the system
              roots = File.listRoots();
         /*SD1)==== Method detectCdDrives() ========================================================\
         |Purpose: To SCAN the system for any drives mounted and add DRIVE LETTER and DRIVE NAME    |
         |         to a Vector. It Also CHECKS if drive CONTAINS any DATA or if it`s EMPTY.         |
         |Variables: (int) i - a loop iterator                                                      |
         |           (String) cdInfo - temporary storage for drive information during drive check   |
         |           (Vector) drives - storage for driveletter and drive name for all drives        |
         |                             This Vector is returned upon function call                   |
         public Vector detectCdDrives(){
              String cdInfo;
              //SCAN system and RETRIEVE drives
              for(int i = 0; i < roots.length; i++){
                   if((fsv.getSystemDisplayName(roots)).equals("")) //--FIND OUT if any DATA on DRIVE
                        cdInfo = fsv.getSystemTypeDescription(roots[i]) + " ";
                   else
                   cdInfo = fsv.getSystemDisplayName(roots[i]);
                   drives.addElement(roots[i].getPath() + " " + cdInfo.substring(0, cdInfo.length()-5));
              return drives;
    FileSystem.java
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.io.File;
    import java.io.*;
    import java.util.Vector;
    public class FileSystem{
         private String driveLetter;
         private Vector root;
         private Vector dirs;
         private Vector files;
         private File dir;
         private File [] allFiles;
         private DefaultMutableTreeNode top;
         /*================= File System Constructor ================================\
         |Purpose: To initialize the conject and to accept drive letter selected in  |
         |         main module                                                       |
         public FileSystem(String dl){
              driveLetter = dl;
        /*================= Method: sortFiles() ====================================\
         |Purpose: To sort content of selected drive, directories (alphabetically),  |
         |         followed by files (alphabeticaly)                                 |
         public void sortFiles(){
              dir = new File (driveLetter);
              allFiles = dir.listFiles();
              root  = new Vector(2,1);
              dirs  = new Vector(0,1);
             files = new Vector(0,1);
             //---- Separate Directories and Files into 2 different vectors
             for(int i = 0; i < allFiles.length; i++){
                   if(allFiles.isDirectory())
                   dirs.add(allFiles[i]);
                   else
                   files.add(allFiles[i]);
              //---- Add elements from dirs and files Vectors into root vector
              for(int i = 0; i < dirs.size(); i++){
                   root.add(dirs.elementAt(i));
              for(int i = 0; i < files.size(); i++){
                   root.add(files.elementAt(i));
    /*================= Method: addNodes() =====================================\
         |Purpose: to build the file structure which will be used to create the tree |
         |Variables: drive = used to accept the drive letter representing the root |
         | top = primary (root) node in the structure) |
    | root = vector of all files in the drive |
         public void addNodes(String drive){
              top = new DefaultMutableTreeNode(drive);
              DefaultMutableTreeNode node = null;
              for(int i = 0; i < root.size(); i++){
                   node = new DefaultMutableTreeNode(root.elementAt(i));
                   top.add(node);
    /*================= Method: getNodes() =====================================\
         |Purpose: To return variable top, which holds the files structure and will |
         | be used to build the tree |
    public DefaultMutableTreeNode getNodes(){
              return top;

Maybe you are looking for

  • My ipod says that I am connected to wifi, but the app store won't load, what do I do?

    I just bought a brand new iPod touch yesterday, and I was trying to learn how to use it. I connected to my University's wifi, (and I know it works because my laptop is on it, and other friends have iPod touches who connect to it). I can connect to th

  • I Pod 80 Classic Will Not Turn On

    I have just received a new iPod 80 Classic and it was working fine. I tried to use it today and it will not turn on or show that it is charging which I assume it is not. I have tried all the instructions and cannot make anything happen. Any ideas? Th

  • RE: Creating Auxiliary objectclasses in Directory 6.3

    Hi, I take it that the above process cant be done using the DSCC console? Is this an oversight by Sun and will it be fixed in a later release please? Ive created a custom objectclass through the front end and doing a search on the cn=schema shows tha

  • Upgrade path for 11.5.10.2 to R12.1.3

    Hi All, We are in the process of upgrading our 11.5.10.2 instance to R12.1.3. Could anyone tell me the upgrade path for this Do we have to mandatorily upgrade first to R12.1.1 and then apply R12.1.3 MP? Also Please confirm if we have any R12.1.3 soft

  • Question re Zone Alarm and WRT54G admin page display problem

    First - thanks to all who posted about Zone Alarm - I was going to exchange my router this weekend - I spent an hour on the phone with tech support and she was trying to get my router updated with v9 through a roundabout way, but I kept getting an er