Problem with JTree while expanding/collapsing a node

Hi,
I'm using a JTree for displaying the file system.
Here, i want that whenever a node get expanded,
it should show the latest files/directories under that node.
Now, what i'm doing is, getting all the files/dir's using files.listFiles(),
under that node and then creating a new node and adding it to parent (all in expand() method).
But, now the problem is, while doing this whenever the parent node get expanded its adding all the latest files/dirs into the previous instance
resulting the same file/dir is displaying twice,thrice.. and so on, as that node is expanded and collapsed.
i tried removeAllChildren() in collapse() method but then that node is notexpanding at all .
Can anybody help me please...
i got stuck b'coz of this only.
Thanks...

Now what i'm doing is every time expand() get called,
i'm comparing all the children of that node in the
current instance with all the children present in the
file system (because there is a possibility that some
file/dir may be added or deleted)
is this the right wy or not?it certainly is not wrong, but as usual, there is more than 1 way to implement this...
b'coz right now i'm getting all the files/dirs that
are newly added but facing some problem if somebody
deletes a file/dir.
i'm still trying to get the solutionthen you should not just compare all the children of the node with the files/dirs but also the other way round. compare the files/dirs with the children to determine if the file/dir still exists and if not remove the node.
or you could check if the file which a node represents exists and if not remove the node.
thomas

Similar Messages

  • Problem with JTree in expanded mode?

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

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

  • 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 remove expand/collapse cross button...??

    Hi all,
    I have forbidden tree collapsing (by default it is fully expanded),
    and I want to remove expand/collapse cross buttons that actually are used to expand/collapse tree nodes.
    Is it possible and can anyone give me advice how i can do this.
    Thanks in advance.

    I tried extending the BasicTreeUI to return nulls for the collapsed and exapnded icons as shown in the code below. For the most part, it works great! However, one can still expand/collapse the tree by clicking on the point where the vertical and horizontal lines connect.
    I guess some one else will take over from here.
    import java.awt.BorderLayout;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.WindowConstants;
    import javax.swing.plaf.basic.BasicTreeUI;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Temp extends JFrame {
         private JTree tree = null;
         public Temp() {
              super("Test");
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              initComponents();
              pack();
              setVisible(true);
         private void initComponents() {
              DefaultMutableTreeNode rootNode =
                   new DefaultMutableTreeNode("User Preferences", true);
              DefaultMutableTreeNode connectionSettingsNode =
                   new DefaultMutableTreeNode("Connection Settings", true);
              DefaultMutableTreeNode sslNode =
                   new DefaultMutableTreeNode("SSL", false);
              DefaultMutableTreeNode firewallNode =
                   new DefaultMutableTreeNode("Firewall", false);
              DefaultMutableTreeNode securityNode =
                   new DefaultMutableTreeNode("Security", true);
              DefaultMutableTreeNode serverCertificatesNode =
                   new DefaultMutableTreeNode("Server Certificates", false);
              DefaultMutableTreeNode clientCertificatesNode =
                   new DefaultMutableTreeNode("Client Certificates", false);
              connectionSettingsNode.add(sslNode);
              connectionSettingsNode.add(firewallNode);
              securityNode.add(serverCertificatesNode);
              securityNode.add(clientCertificatesNode);
              rootNode.add(connectionSettingsNode);
              rootNode.add(securityNode);
              tree = new JTree(rootNode);
              JScrollPane scroller = new JScrollPane(tree);
              getContentPane().add(scroller, BorderLayout.CENTER);
              tree.setUI(new MyTreeUI());
              //tree.setShowsRootHandles(false);
         public static void main(String args []) {
              new Temp();
         class MyTreeUI extends BasicTreeUI {
              public Icon getCollapsedIcon() {
                   return null;
              public Icon getExpandedIcon() {
                   return null;
    }Sai Pullabhotla

  • Problem with flow of expandable fields

    Hi everyone,
    I have important problem with flow of expandable fields in table in dynamic PDF form. The issue I am talking about you can see at the top of column 3 on page 2 in PDF in link below.
    Here is uploaded PDF form and sample XML data (form has import button and is ReaderExtended that you can easily test it and see my problem):
    http://www.speedyshare.com/718224676.html
    Generally I have created table with 3 columns using Table object (each field has allow multiple lines selected and expand to fit).  It is closed in FormBody subform which is flowed subform.
    Row in table is repeatable and has “is allow to break page” setting set on.
    Sometimes when there is a lot of text and row page break there is problem with flow.
    For example text from one rows overlaps on text from next row.
    I tried to solve this problem by changing row height, indents, font size, line spacing but always when I thought that I have fixed it  I got another data which generated the same flow problem.
    Did anyone met this problem earlier and found solution to this issue? This is really important for me and I am really in dead end so any hints would be really helpful.
    I am using Adobe Livecycle Designer 8.1 and PDF form target is 8.
    I really appreciate any help in this problem.
    Thanks,
    Kamil Dłutowski

    I posted link to my form in my first post.
    Here it is: http://www.speedyshare.com/718224676.html

  • Compilation problem with templates while using option -m64

    Hi,
    I have compilation problem with template while using option -m64.
    No problem while using option -m32.
    @ uname -a
    SunOS snt5010 5.10 Generic_127111-11 sun4v sparc SUNW,SPARC-Enterprise-T5220
    $ CC -V
    CC: Sun C++ 5.9 SunOS_sparc Patch 124863-01 2007/07/25
    Here is some C++ program
    ############# foo5.cpp #############
    template <typename T, T N, unsigned long S = sizeof(T) * 8>
    struct static_number_of_ones
    static const T m_value = static_number_of_ones<T, N, S - 1>::m_value >> 1;
    static const unsigned long m_count = static_number_of_ones<T, N, S - 1>::m_count + (static_number_of_ones<T, N, S - 1>::m_value & 0x1);
    template <typename T, T N>
    struct static_number_of_ones<T, N, 0>
    static const T m_value = N;
    static const unsigned long m_count = 0;
    template <typename T, T N>
    struct static_is_power_of_2
    static const bool m_result = (static_number_of_ones<T,N>::m_count == 1);
    template <unsigned long N>
    struct static_number_is_power_of_2
    static const bool m_result = (static_number_of_ones<unsigned long, N>::m_count == 1);
    int main(int argc)
    int ret = 0;
    if (argc > 1)
    ret += static_is_power_of_2<unsigned short, 16>::m_result;
    ret += static_is_power_of_2<unsigned int, 16>::m_result;
    ret += static_is_power_of_2<unsigned long, 16>::m_result;
    ret += static_number_is_power_of_2<16>::m_result;
    else
    ret += static_is_power_of_2<unsigned short, 17>::m_result;
    ret += static_is_power_of_2<unsigned int, 17>::m_result;
    ret += static_is_power_of_2<unsigned long, 17>::m_result;
    ret += static_number_is_power_of_2<17>::m_result;
    return ret;
    Compiation:
    @ CC -m32 foo5.cpp
    // No problem
    @ CC -m64 foo5.cpp
    "foo5.cpp", line 20: Error: An integer constant expression is required here.
    "foo5.cpp", line 36: Where: While specializing "static_is_power_of_2<unsigned long, 16>".
    "foo5.cpp", line 36: Where: Specialized in non-template code.
    "foo5.cpp", line 26: Error: An integer constant expression is required here.
    "foo5.cpp", line 37: Where: While specializing "static_number_is_power_of_2<16>".
    "foo5.cpp", line 37: Where: Specialized in non-template code.
    "foo5.cpp", line 20: Error: An integer constant expression is required here.
    "foo5.cpp", line 43: Where: While specializing "static_is_power_of_2<unsigned long, 17>".
    "foo5.cpp", line 43: Where: Specialized in non-template code.
    "foo5.cpp", line 26: Error: An integer constant expression is required here.
    "foo5.cpp", line 44: Where: While specializing "static_number_is_power_of_2<17>".
    "foo5.cpp", line 44: Where: Specialized in non-template code.
    4 Error(s) detected.
    Predefined macro:
    @ CC -m32 -xdumpmacros=defs foo5.cpp | & tee log32
    @ CC -m64 -xdumpmacros=defs foo5.cpp | & tee log64
    @ diff log32 log64
    7c7
    < #define __TIME__ "09:24:58"
    #define __TIME__ "09:25:38"20c20
    < #define __sparcv8plus 1
    #define __sparcv9 1[snipped]
    =========================
    What is wrong?
    Thanks,
    Alex Vinokur

    Bug 6749491 has been filed for this problem. It will be visible at [http://bugs.sun.com] in a day or two.
    If you have a service contract with Sun, you can ask to have this bug's priority raised, and get a pre-release version of a compiler patch that fixes the problem.
    Otherwise, you can check for new patches from time to time at
    [http://developers.sun.com/sunstudio/downloads/patches/]
    and see whether this bug is listed as fixed.

  • Hello. I have problem here can someone plz help. I have usb of 32 gb but i have problem with it while i was trying to partition of it and it fails and my usb disappear from finder and desktop i have tried every possible thing but nothing  works .

    Hello. I have problem here can someone plz help. I have usb of 32 gb but i have problem with it while i was trying to partition of it and it fails and my usb disappear from finder and desktop i have tried every possible thing but nothing  works .

    Yea i tried in disk utility and its got faiiled and the partitation has deleted and when i tried  to replug the  usb  msg show up by saying  usb not compaitnle. With this mac  and  take me to disk utility  and thanks for replying

  • Can anyone please help me, I'm having problems with sound while watching video clips using flash player using Internet Explorer\

    Can anyone please help me, I'm having problems with sound while watching video clips using flash player & Internet Explorer

    There's a good chance that this is a known issue.  We'll have a Flash Player 18 beta later this week that should resolve this at http://www.adobe.com/go/flashplayerbeta/

  • Problem with JTree converting Node to string

    I have a problem that I cannot slove with JTree. I have a DefaultMutalbeTreeNode and I need its parent and convert to string. I can get its parent OK but cannot convert it to string.
    thisnode.getParent().toString() won't work and gives an exception
    thisnode.getParent() works but how do I convert this to string to be used by a database.
    Thanks
    Peter Loo

    You are using the wrong method to convert it to a String array.
    Try replacing this line:
    String[] tabStr = (String[])strList.toArray();
    With this line:
    String[] tabStr = (String[])strList.toArray( new String[ 0 ] );
    That should work for you.

  • Problem with JTree.isExpanded()

    Working with a JTree, I encountered into a strange behavior - I hope someone could explain me...
    For exporting a tree I need the information whether nodes are expanded or not.
    The first strange thing is that the root always seems to be collapsed - but this I can handle somehow.
    The problem is, that a expanded node containing a leaf, is reported as collapsed - but it is not. Why?
    Here the output of a expand-checking method, which prints the state of the node and its parents.
    (the "+" indicates a expanded node, the "-" indicated a collapsed node)
    + - Abasdf
    + - EP/asdf
    + - - Prosadf
    + - - - Altasdf
    + - - - - V1sadf
    + - - - - - 059asdf
    + - - - - - - 059asdf
    + - - - - - - + 059asdf
    + - - - - - - + + this_is_a_leafWhy is the expanded node containing the leaf reported as collapsed?
    I'm using the following for checking if a node is expanded:
    view.isExpanded(node.getIndex())I also tried this - with the same wrong result:
    view.isExpanded(view.getPathForRow(node.getIndex()))Any hint is highly appretiated.

    I was not able to reproduce your problemimport javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeNode;
    import java.util.Random;
    import java.util.Enumeration;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    public class HamsterChipsyTest extends JPanel {
         private static final Random RANDOM = new Random(System.currentTimeMillis());
         private JTree theTree;
         private DefaultTreeModel theTreeModel;
         private DefaultMutableTreeNode theRoot;
         public HamsterChipsyTest() {
              super(new BorderLayout());
              theRoot = createRandomNode();
              addNodes(theRoot, 0, 2);
              theTreeModel = new DefaultTreeModel(theRoot);
              theTree = new JTree(theTreeModel);
              add(new JScrollPane(theTree), BorderLayout.CENTER);
              add(new JButton(new AbstractAction("dump nodes' extension state") {
                   public void actionPerformed(ActionEvent e) {
                        dumpExtensionState(theRoot);
              }), BorderLayout.NORTH);
         private void dumpExtensionState(DefaultMutableTreeNode aTreeNode) {
              TreeNode[] path = aTreeNode.getPath();
              for (int i = 0; i < path.length; i++) {
                   System.out.print('-');
              System.out.println(" " + aTreeNode.getUserObject().toString() + " " + theTree.isExpanded(new TreePath(path)));
              Enumeration children  = aTreeNode.children();
              while(children.hasMoreElements()) {
                   DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement();
                   dumpExtensionState(child);
         private static void addNodes(DefaultMutableTreeNode aParent, int aCurrentDepth, int aMaxDepth) {
              if (aCurrentDepth >= aMaxDepth) return;
              int nodeCount = RANDOM.nextInt(3);
              for (int i = 0; i < nodeCount + 1; i++) {
                   DefaultMutableTreeNode child = createRandomNode();
                   aParent.add(child);
                   addNodes(child, aCurrentDepth + 1, aMaxDepth);
         private static DefaultMutableTreeNode createRandomNode() {
              char[] chars = new char[5];
              for (int i = 0; i < chars.length; i++) {
                   chars[i] = (char)('a' + RANDOM.nextInt(26));
              return new DefaultMutableTreeNode(new String(chars));
         public static void main(String[] args) {
              final JFrame frame = new JFrame(HamsterChipsyTest.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new HamsterChipsyTest());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.show();
    }

  • Problems with JTree

    Hi,
         I have a few problems while working with JTree. Here is the detail:
    I get the name of the required file from JFileChooser and add it to the root node of JTree using
    root.add(new DefaultMutableTreeNode(fileName));
    The following happens.
    1) If I add it to root, it is not added(or shown,at least) there.
    2) if I add it to a child of root, then if the node is collapsed before the event, after the event when it is expanded fileName is there.
    3) However if it is expanded before adding the fileName,the fileName is not added (or not shown).
    4) Further if I add another file(whether the node is collapsed or expanded) it is also not shown, means that it works only once during the life-time of the application.
    5) I have used JFrame and call repaint() for both the JFrame and JTree but the problem is still there.
         Please help me in solving this problem.
    Thanks in advance,
    Hamid Mukhtar,
    [email protected]
    H@isoft Technologies.

    Try doing this...
    tree.getModel().reload(node)
    node here is the node to which a new node is added

  • Focus Problem with JTree and Menus

    Hi all,
    I have a problem with focus when editing a JTree and selecting a menu. The problem occurs when the user single clicks on a node, invoking the countdown to edit. If the user quickly clicks on a menu item, the focus will go to the menu item, but then when the countdown finishes, the node now has keyboard focus.
    Below is code to reproduce the problem. Click on the node, hover for a little bit, then quickly click on the menu item.
    How would I go about fixing the problem? Thanks!
    import java.awt.Container;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    public class MyTree extends JTree {
         public MyTree(DefaultTreeModel treemodel) {
              setModel(treemodel);
              setRootVisible(true);
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JMenuBar bar = new JMenuBar();
              JMenu menu = new JMenu("Test");
              JMenuItem item = new JMenuItem("Item");
              menu.add(item);
              bar.add(menu);
              frame.setJMenuBar(bar);
              Container contentPane = frame.getContentPane();
              contentPane.setLayout(new GridLayout(1, 2));
              DefaultMutableTreeNode root1 = new DefaultMutableTreeNode("Root");
              root1.add(new DefaultMutableTreeNode("Root2"));
              DefaultTreeModel model = new DefaultTreeModel(root1);
              MyTree tree1 = new MyTree(model);
              tree1.setEditable(true);
              tree1.setCellEditor(
                   new ComponentTreeCellEditor(
                        tree1,
                        new ComponentTreeCellRenderer()));
              tree1.setRowHeight(0);
              contentPane.add(tree1);
              frame.pack();
              frame.show();
    import java.awt.FlowLayout;
    import java.util.EventObject;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreeCellRenderer;
    public class ComponentTreeCellEditor
         extends DefaultTreeCellEditor
         implements TreeCellEditor {
         private String m_oldValue;
         private TreeCellRenderer m_renderer = null;
         private DefaultTreeModel m_model = null;
         private JPanel m_display = null;
         private JTextField m_field = null;
         private JTree m_tree = null;
         public ComponentTreeCellEditor(
              JTree tree,
              DefaultTreeCellRenderer renderer) {
              super(tree, renderer);
              m_renderer = renderer;
              m_model = (DefaultTreeModel) tree.getModel();
              m_tree = tree;
              m_display = new JPanel(new FlowLayout(FlowLayout.LEFT));
              m_field = new JTextField();
              m_display.add(new JLabel("My Label "));
              m_display.add(m_field);
         public java.awt.Component getTreeCellEditorComponent(
              JTree tree,
              Object value,
              boolean isSelected,
              boolean expanded,
              boolean leaf,
              int row) {
              m_field.setText(value.toString());
              return m_display;
         public Object getCellEditorValue() {
              return m_field.getText();
          * The edited cell should always be selected.
          * @param anEvent the event that fired this function.
          * @return true, always.
         public boolean shouldSelectCell(EventObject anEvent) {
              return true;
          * Only edit immediately if the event is null.
          * @param event the event being studied
          * @return true if event is null, false otherwise.
         protected boolean canEditImmediately(EventObject event) {
              return (event == null);
    }

    You can provide a cell renderer to the JTree to paint the checkBox.
    The following code checks or unchecks the box with each click also:
    _tree.setCellRenderer(new DefaultTreeCellRenderer()
      private JCheckBox checkBox = null;
      public Component getTreeCellRendererComponent(JTree tree,
                                                    Object value,
                                                    boolean selected,
                                                    boolean expanded,
                                                    boolean leaf,
                                                    int row,
                                                    boolean hasFocus)
        // Each node will be drawn as a check box
        if (checkBox == null)
          checkBox  = new JCheckBox();
          checkBox .setBackground(tree.getBackground());
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        checkBox.setText(node.getUserObject().toString());
        checkBox.setSelected(selected);
        return checkBox;
    });

  • Problem with Jtree and a checkbox

    Hello,
    I have a problem with my tree implementation.
    I create a tree and i want to add a checkbox in each node.
    this is my code :
    DefaultMutableTreeNode root;
    root = new DefaultMutableTreeNode(new JCheckBox());
    DefaultTreeModel model = new DefaultTreeModel(root);
    _tree = new JTree(model);
    eastpane.add(tree);
    THe problem is that my checkbox doesn't appear. And a message appears
    instead of my checkbox.
    But my tree appears.
    Can anyone help me .
    Thanks

    You can provide a cell renderer to the JTree to paint the checkBox.
    The following code checks or unchecks the box with each click also:
    _tree.setCellRenderer(new DefaultTreeCellRenderer()
      private JCheckBox checkBox = null;
      public Component getTreeCellRendererComponent(JTree tree,
                                                    Object value,
                                                    boolean selected,
                                                    boolean expanded,
                                                    boolean leaf,
                                                    int row,
                                                    boolean hasFocus)
        // Each node will be drawn as a check box
        if (checkBox == null)
          checkBox  = new JCheckBox();
          checkBox .setBackground(tree.getBackground());
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        checkBox.setText(node.getUserObject().toString());
        checkBox.setSelected(selected);
        return checkBox;
    });

  • Sorting JTree results in collapse of nodes!

    I've searched and searched and can not find a good example of how to do this. I've found many threads that pose the question with the only answer being something like "I figured it out, thanks anyway".
    My problem:
    I've got a tree, many nodes, many depths. I'd like to sort it. My present algorithm is to traverse the tree and sort the list of children of each node. Once I sort the children, obviously the indexes have changed, so you must correct them.
    I've tried:
    remove all children from the parent
    add the children in sorted order
    If I do that using something like parent.remove and parent.insert, thats fine as long as no children UNDER those children have been expanded. If they have, then I'm not accounting for them and thus the tree continues to show those children under the wrong nodes once the sorted nodes are added.
    If I do that using something like model.removeNodeFromParent and model.insertNodeInto, then the entire tree will collapse up to the node sorted on.
    Either way sucks!
    I've also tried passing Arrays.sort my own comparator that, depending on the compare outcome, will do the removeFromParent and insertNodeInto on the fly. This results in NOT collapsing the entire tree (probably because all nodes are never removed) however it seems like on a descending sort the nodes get messed up. I assumed this was because I was reordering them on the fly in the tree...but now that I'm thinking about it, maybe I was doing something else wrong.
    In any case, is there a standard proceedure for doing this? Why does it seem so difficult? I've spent a good two days on this. Crazy!

    Found this in another thread after all, might be my solution:
         public Vector savePaths() {
              Vector v = new Vector();
              for (int i=0; i<getTree().getRowCount(); i++) {
                   if (getTree().isExpanded(i)) {
                        v.add(getTree().getPathForRow(i));
              return v;
         public void loadPaths(Vector v) {
              for (int i=0; i><v.size(); i++) {          
                   getTree().expandPath((TreePath) v.get(i));
         }

  • Problem with JTree and memory usage

    I have problem with the JTree when memory usage is over the phisical memory( I have 512MB).
    I use JTree to display very large data about structure organization of big company. It is working fine until memory usage is over the phisical memory - then some of nodes are not visible.
    I hope somebody has an idea about this problem.

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

Maybe you are looking for

  • Two different streamings on two AppleTV at the same time?

    Hey guys, I'd like to buy a second Apple TV. First: Is it possible to stream different content on each AppleTV at the same time by using one computer with only one iTunes? Second: If the first question is answerred by "no", is it possible to stream t

  • Cut video clips from Apple Imac

    Hoping somebody might be able to help me out..I'm not very techie when if comes to video editing etc on my Apple Imac. I have a number of large video files that are far too long in playing length to post to you tube so I am looking for the easiest wa

  • Flash Player is enabled, ActiveX Filtering disabled, yet Flash videos will not play in Internet Explorer 11

    I have enabled Flash Player in add-ons for Internet Explorer 11 for Windows 8.1. I also disabled ActiveX Filtering as instructed while trouble shooting... Yet, videos still will not play on webpages shown in Internet Explorer. How can I fix this, sin

  • J2EE Security Question

    I am developing an e-commerce application using J2EE1.3.This application enable users to set up their own accounts without administrative intervention.They are prompt to provide some personal information as well as a username and password.This inform

  • I knew this once but forgot how to install new fonts.

    I have SCAL( sure cuts a lot) for my Cricut machine( a computerised cutting machine used mainly in crafting. I needed some clearer fonts to use with it BUT now I have forgotten how to make them available to my Apps. Please can someone refresh my memo