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

Similar Messages

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

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

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

  • 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

  • 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

  • Problem with JTree custom renderer when editing

    I have a JTree which uses a custom renderer to display my own icons for different types of nodes. The problem I am having is when I setEditable to true and then attept to edit a node the icon switches back to the default icon, as soon as I am done editing it goes back.
    What I am doing wrong?

    Here is my rendererer
    public class DeviceTreeRenderer extends DefaultTreeCellRenderer implements GuiConstants {
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
          JLabel returnValue = (JLabel)super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
          if (value != null) {
             returnValue.setToolTipText(value.toString());
          if (value instanceof Device) {
             returnValue.setIcon(TREE_DEVICE);
             if (!((Device)value).isAlive()) {
                returnValue.setEnabled(false);
          else if (value instanceof GuiPanelGroup) {
             if (expanded) {
                returnValue.setIcon(TREE_PANEL_GROUP_OPEN);
             else {
                returnValue.setIcon(TREE_PANEL_GROUP_CLOSED);
          else if (value instanceof GuiPanel && ((GuiPanel)value).isDirty()) {
             returnValue.setIcon(TREE_PANEL_DIRTY);
          return returnValue;
    }Here is my editor:
    public class WwpJTreeCellEditor extends DefaultTreeCellEditor implements GuiConstants {
          private WwpJTree tree;
           * Creates a new WwpJTreeCellEditor.
           * @param tree The WwpJTree to associate with this editor.
          public WwpJTreeCellEditor(WwpJTree tree) {
             super(tree, (DefaultTreeCellRenderer)tree.getCellRenderer());
             this.tree = tree;
           * Overrides the default isCellEditable so that we check the isEditable() method
           * of the WwpJTreeNodes.
           * @param e An EventObject.
          public boolean isCellEditable(EventObject e) {
             boolean returnValue = super.isCellEditable(e);
             if (returnValue) {
                WwpJTreeNode node = this.tree.getSelectedNode();
                if (node == null || !node.isEditable() || node.isDragging()) {
                   returnValue = false;
             return returnValue;
       }In my JTree I make these calls:
    super.setCellRenderer(new DeviceTreeRenderer());
    super.setCellEditor(new WwpJTreeCellEditor(this));
    super.setEditable(true);

  • Problem with jtree selection

    Hi all,
    I've got a JTree that represents a sort of data that I'm going to change dynamically in my application. I'd like to reset the selection of the user to the leaf she has selected before the change to the tree structure.
    First of all my tree uses DefaultMutableTreeNode to build each node, and each DefaultMutableTreeNode contains a SingleKeyValue object, that is a key-value object (two strings) and that has an hashcode defined as follows:
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         public int hashCode() {
              return this.key.hashCode();
         I hope the hashcode can help me finding the right object even when its value changes (but the key is the same). The construction of the tree is the following:
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("The root");
    // iterate and build each node
    SingleKeyValue object = new SingleKeyValue("key","value");
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(object);
    root.add(node);
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree  tree = new JTree(model);             
                so the tree is associated to a DefaultTreeModel. Then, when I need to change something in the tree I rebuild the tree and all leafs (with the SingleKeyValues) and rebuild the model:
              TreeModel treeModel = this.myTree.getModel();
              TreeSelectionModel selectionModel = this.myTree.getSelectionModel();
              DefaultTreeModel defaultTreeModel = null;
              DefaultTreeSelectionModel defaultTreeSelectionModel = null;
              TreePath selectedPath = null;
              TreeNode root = null;
              Logger.info("SimpleTreePanel.refreshDatabaseView: treemodel "+treeModel + " selectionModel " + selectionModel);
              if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
                   defaultTreeModel = (DefaultTreeModel) treeModel;
                   root = this.getRoot();
                   // get the selection
                   if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                        defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                        selectedPath = defaultTreeSelectionModel.getSelectionPath();
                        Logger.warn("Selection path of the tree: "+selectedPath);
                   // rebuild the tree
                   defaultTreeModel.setRoot(root);
                   // set the selected element
                   defaultTreeSelectionModel.setSelectionPath(selectedPath);The problem is that after the above code the tree is all closed, no leaf are selected. I guess the problem is with the SingleKeyValueObject because I've tried the default model and it works with, for example, simple strings. Any idea about?
    Thanks,
    Luca

    Here's a complete test program that creates a few SingleKeyValue objetcs (objects with a key and a description) and that then places them into a JTree using the DefaultMutableTreeNode. After that, the selection of user is took and one node is changed, but while the selection is working, the reload/refresh of the tree is not.
    Any idea about how to work on it?
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         // constants related to the type of the table this object refers to
         public static final String COMPETENCE = "competenza";
         public static final String FAMILY            = "famiglia_competenza";
         public static final String ROLE              = "ruolo";
         public static final String PROVINCE      = "provincia";
         public static final String KNOWLEDGE  = "titolo_studio";
         public final static String OBJECTIVE      = "obiettivo";
         public final static String PERSON         = "persona";
         public SingleKeyValue( String key, String value, String table){
              super();
              this.key = key;
              this.value = value;
              this.SQLTable = table;
          * @return the key
         public final String getKey() {
              return key;
          * @param key the key to set
         public final void setKey(String key) {
              this.key = key;
          * @return the value
         public final String getValue() {
              return value;
          * @param value the value to set
         public final void setValue(String value) {
              this.value = value;
          * Shows this element.
         public String toString(){
              String ret;
              if( this.showKey ){
                   ret =  this.label + this.key +" { "+ this.value +" }";
              else
                   ret = this.label + this.value;
              // trim the string
              if( ret.length() > this.maxLength )
                   return ret.substring(0 , this.maxLength);
              else
                   return ret;
          * The hash code of this object is the hash code of the key.
          * @return the hash code of the key of the object
         public int hashCode() {
              return this.key.hashCode();
          * Returns true if the object passed is a single key value equals (i.e., with the same key) of this one.
         public boolean equals(Object o){
              if( o== null || (! (o instanceof SingleKeyValue) ) )     return false;
              else
                   return (this.hashCode() == o.hashCode());
         public static void main(String argv[]) throws Exception{
             SingleKeyValue skv1 = new SingleKeyValue("Key1","Description1", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv2 = new SingleKeyValue("Key1a","Description1a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv3 = new SingleKeyValue("Key1b","Description1b", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv4 = new SingleKeyValue("Key2","Description2", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv5 = new SingleKeyValue("Key2a","Description2a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv6 = new SingleKeyValue("Key2b","Description2b", SingleKeyValue.COMPETENCE);
             DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root");
             DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(skv1);
             DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(skv2);
             DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(skv3);
             DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(skv4);
             DefaultMutableTreeNode node5 = new DefaultMutableTreeNode(skv5);
             DefaultMutableTreeNode node6 = new DefaultMutableTreeNode(skv6);
             rootNode.add(node1);
             node1.add(node2);
             node1.add(node3);
             rootNode.add(node4);
             node4.add(node5);
             node4.add(node6);
             JTree tree = new JTree(rootNode);
             JFrame f = new JFrame("Tree try");
             f.add( new JScrollPane(tree) );
             f.setSize(300,300);
             f.setVisible(true);
             System.out.println("Please select a node within 10 seconds");
             Thread.sleep(10000);
             // now get the user selection
         TreeModel treeModel = tree.getModel();
         TreeSelectionModel selectionModel = tree.getSelectionModel();
         DefaultTreeModel defaultTreeModel = null;
         DefaultTreeSelectionModel defaultTreeSelectionModel = null;
         TreePath selectedPath = null;
         TreeNode root = null;
         if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
              defaultTreeModel = (DefaultTreeModel) treeModel;
              // get the selection
              if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                   defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                   selectedPath = defaultTreeSelectionModel.getSelectionPath();
              // rebuild the tree
              node1.setUserObject(new SingleKeyValue("key20","key changed",SingleKeyValue.FAMILY));
              defaultTreeModel.reload();
              // set the selected element
              defaultTreeSelectionModel.setSelectionPath(selectedPath);
    }

  • Problem with  JTree and JPopupMenu

    Hi,
    I'm using a JPopupMenu with a JPanel in it. In the panel
    I want to have a JTree. I can build the tree without
    problems but when I try to "go down" in the tree it
    vanishes. This happens only the first time that I
    access a node. When I initialize the menu a second
    time the node I just pressed works fine.
    What is the problem????
    Here is a sample of my code.
    popUpMenu = new JPopupMenu();
    thePanel = new JPanel();
    thePanel .setLayout(new GridBagLayout());
    popUpMenu .add(thePanel );
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("The top");
    DefaultMutableTreeNode secondNode = null;
    DefaultMutableTreeNode firstNode = null;
    firstNode = new DefaultMutableTreeNode("One node");
    top.add(firstNode);
    secondNode= new DefaultMutableTreeNode("One node");
    firstNode.add(secondNode);
    buildConstraints(gbc, 1, 0, 1, 5, 5, 5, 5, 2, 1); //My contraintsmethod
    JTree tree = new JTree(top);
    thePanel .add(tree, gbc);

    Mate, why are you putting a JPanel in a JPopupMenu? I'd be interested to look at a screenshot of this.
    Mitch

  • Problem with Jtree to xml tranform..how to set/get parent of a node?

    Hi,
    I am trying to develop xml import/export module.In import wizard, I am parsing the xml file and the display it in Jtree view using xml tree model which implements TreeModel and xml tree node.I am using jaxp api..
    It is workin fine.
    I got stuck with removal of selected node and save it as a new xml.
    I am not able to get parent node of selected node in remove process,itz throwing null.I think i missed to define parent when i load treemodel.Plz help me out..give some ideas to do it..
    thanks
    -bala
    Edited by: r_bala on May 9, 2008 4:44 AM

    there's no way anyone can help you without seeing your code.

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

  • Problems with JTree using removeSelectedPath

    Hi. In my application, I would like the user to be able to select anything in the JTree with the following exceptions:
    - a selected node cannot be an ancestor of another node
    - a selected node must be of the same node type
    Let's say I have five different node types (a,b,c,d,e) that correspond to each level of the tree.
    root
    |-node 1 (node type a)
    | |-node 2 (node type b)
    | | |- node 3 (node type c)
    | |- node 4 (node type b)
    |-node 5 (node type a)
    A user would be able to select nodes 2 and 4 since they are the same type and node 4 isn't an ancestor of node 2. So, if the user clicked on node 2, held the shift key and clicked on node 4, I'd like to automatically unselect node 3.
    I tried to do this by adding a TreeSelectionListener, but each call to removeSelectionPath calls itself again since the tree is being "selected".
    Does anyone have an elegant way? I was thinking about removing the listener when the valueChanged() method was called and then add it back when I'm done modifying the tree...
    TIA,
    Chester

    The not-so-elegant way is to use the TreeSelectionListener (I don't see how you can avoid using that) and to incorporate a boolean flag in your program that is set to true when your program is changing the selection (via removeSelectionPath) and to false otherwise. Then your listener can check the flag to see who's making the change. Not so elegant, but not as inelegant as removing the listener and then adding it back.

  • Problem with JTree editing icons

    Hello,
    I want to edit another icons than the default icons in JTree object.
    I look in the javadoc at the several methods, but I do not find a method witch can give me the possibility to setup the collapsed and expanded icon.
    If some one now how to do that, it will be cool.
    Thanks.

    I write this class :
    public class SampleTreeCellRenderer extends TreeCellRenderer
    /** Font used if the string to be displayed isn't a font. */
    static protected Font defaultFont;
    /** Icon to use when the item is collapsed. */
    static protected ImageIcon collapsedIcon;
    /** Icon to use when the item is expanded. */
    static protected ImageIcon expandedIcon;
    /** Color to use for the background when selected. */
    static protected final Color SelectedBackgroundColor=Color.yellow;
    static
         try {
         defaultFont = new Font("SansSerif", 0, 12);
    } catch (Exception e) {}
         try {
         collapsedIcon = new ImageIcon("images/collapsed.gif");
         expandedIcon = new ImageIcon("images/expanded.gif");
         } catch (Exception e) {
         System.out.println("Couldn't load images: " + e);
    public SampleTreeCellRenderer() {
    super();
    public SampleTreeCellRenderer(String collapsedImagePath,String expandedImagePath) {
    super();
         try {
         if (collapsedImagePath!=null) collapsedIcon = new ImageIcon(collapsedImagePath);
         if (expandedImagePath!=null) expandedIcon = new ImageIcon(expandedImagePath);
         } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setCollapsedIcon(String path) {
    try {
    if (path!=null) collapsedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setExpandedIcon(String path) {
    try {
    if (path!=null) expandedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    /** Whether or not the item that was last configured is selected. */
    protected boolean selected;
    public Component getTreeCellRendererComponent(
    JTree tree, Object value,     
    boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus) {
         Font font;
         String stringValue = tree.convertValueToText(value, selected,expanded,leaf,row,hasFocus);
         /* Set the text. */
         setText(stringValue);
         /* Tooltips used by the tree. */
         setToolTipText(stringValue);
         /* Set the image. */
         if(expanded) { setIcon(expandedIcon); }
         else if(!leaf) { setIcon(collapsedIcon);}
    else { setIcon(null);}
         /* Update the selected flag for the next paint. */
         this.selected = selected;
         return this;
    public void paint(Graphics g) {
         super.paint(g);
    } // end of class SampleTreeCellRenderer
    I test it but I do not understand why it do not display the icons.

  • Problem with JTree

    Hi All,
    Can anyone please help me in writing a method which will take a JTree/TreeNode/MutableTreeNode and a string as parameters, and then search the JTree/TreeNode/MutableTreeNode for that particular string (which will be the name of a node/leaf in the tree), and then expand the JTree to show the node/leaf?
    Thanx a lot in advance,
    Best Regards,
    Debopam.

    Here's something:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class Test extends JFrame {
        private TreePanel treePanel;
        public Test () {
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (treePanel = new TreePanel ());
            getContentPane ().add (new SearchPanel (), BorderLayout.SOUTH);
            pack ();
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setLocationRelativeTo (null);
            setTitle ("Test");
            setVisible (true);
        public Dimension getPreferredSize () {
            return new Dimension (600, 600);
        private class TreePanel extends JPanel {
            private DefaultTreeModel model;
            private JTree tree;
            public TreePanel () {
                model = new DefaultTreeModel (createRoot ());
                tree = new JTree (model);
                tree.setRootVisible (false);
                tree.setShowsRootHandles (true);
                setLayout (new BorderLayout ());
                add (new JScrollPane (tree));
            private TreeNode createRoot () {
                DefaultMutableTreeNode root = new DefaultMutableTreeNode ("");
                add (root, 1, 3);
                return root;
            private void add (DefaultMutableTreeNode node, int i, int n) {
                for (int l = 0; l < 26; l ++) {
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode (((String) node.getUserObject ()) + (char) ('a' + l));
                    if (i < n) {
                        add (child, i + 1, n);
                    node.add (child);
            public void searchAndExpand (String text) {
                TreeNode[] path = search ((DefaultMutableTreeNode) model.getRoot (), text);
                if (path != null) {
                    TreePath treePath = new TreePath (path);
                    tree.scrollPathToVisible (treePath);
                    tree.setSelectionPath (treePath);
            private TreeNode[] search (DefaultMutableTreeNode node, Object object) {
                TreeNode[] path = null;
                if (node.getUserObject ().equals (object)) {
                    path = model.getPathToRoot (node);
                } else {
                    int i = 0;
                    int n = model.getChildCount (node);
                    while ((i < n) && (path == null)) {
                        path = search ((DefaultMutableTreeNode) model.getChild (node, i), object);
                        i ++;
                return path;
        private class SearchPanel extends JPanel {
            public SearchPanel () {
                JTextField searchField = new JTextField (10);
                searchField.addActionListener (new ActionListener () {
                    public void actionPerformed (ActionEvent event) {
                        treePanel.searchAndExpand (((JTextField) event.getSource ()).getText ());
                setLayout (new GridBagLayout ());
                add (searchField, new GridBagConstraints ());
        public static void main (String[] parameters) {
            new Test ();
    }Kind regards,
      Levi

Maybe you are looking for

  • Upload Module Pool program

    Hi Experts,                     I have developed a Module Pool Program in IDES. Unfortunately the ides system is crashed. But I took the back up of the program. But I dont have any idea of how to upload the program into ides again. Please let me know

  • Error - The request could not be performed due to an error from the I/O device

    Hello,  I have a Hyper-V server with a few virtual machines.  The host runs Windows Server 2012 R2 with Hyper-V.  VMs are Windows Server 2012R2 Generation 2 and Windows Server 2003 Generation 1.  All VMs running on VHDX on local host disks, no raid,

  • CIF from multiple R/3 systems

    Hi, I have the problem when CIF materials from two different R/3 systems. Used customer exit to prefix materials based on BSGs. The issue is that even materials are getting cretaed in MATMAP but some of materials are not getting created in MATKEY. Th

  • RE: GOOD ISSUE...POSTED PROBLEM

    Dear Sap experts, Please advise me that material  qty  2 pcs and reservation 1 pc we checked in material document (MB51) ,  material qty is 2 pcs , and have already done reservation of same material of 1 pc... when we post good issue  then my system

  • How do I compress a PDF so I can email it?

    I need to compress a pdf file. bought the converter to convert to windows but it wont allow me to compress or email. Acrobat now says its wants me to pay another fee? I just purchased the converter