Displaying nodes in a JTree with different icons

Please can you help me? I have set up a JTree that handles different icons for each item in the tree. The items are all independent and there is no way of grouping them together, so to get around the problem of displaying them in the tree I have stored them in array of images, such that each row in the tree maps to the correct element of the tree (or so I thought).
However, my overridden version of getTreeCellRendererComponent() displays interesting behaviour. If one of the branches in tree is collapsed, then the number of rows displayed in the tree differs from when it is expanded. This renders my use of an array useless because it doesn't map to what I thought was the structure of the tree and my icons do not align to the correct textual information.
How can I map my images to the tree so that it displays correctly when the branches are expanded or collapsed?

You need to be able to figure out what icon to display based on the object that the tree cell is rendering. In other words, the object should have an attribute that you can query that tells your cell renderer what icon to use. If all else fails, change your object to contain a reference to the icon that should be displayed next to it.

Similar Messages

  • Display amount in ALV Grid with different Decimal Places based on Currency

    HI Experts,
    Working with ALV Report i have one Amount field NETWR which is having Length 15 and Decimal Places 2.
    we have two different types of currency's AED and KWD and AED having 2 decimal Places and KWD having 3 decimal places.
    im using FM: REUSE_ALV_GRID_DISPLAY for Display. value storing in Table was like this
    AED---22.56
    KWD---225.65
    i need to display values like AED : 22.56

    HI Experts,
    Working with ALV Report i have one Amount field NETWR which is having Length 15 and Decimal Places 2. we have two different types of currency's AED and KWD and AED having 2 decimal Places and KWD having 3 decimal places.
    im using FM: REUSE_ALV_GRID_DISPLAY for Display. value storing in Table was like this
    AED---22.56
    KWD---225.65 (converting this value to 22.565 using BAPI_CURRENCY_GETDECIMALS according to currency in my Report)
    i need to display values like AED : 22.56
                                             KWD---22.565 but here field is NETWR with 2 decimal.
    Need to Display amount in ALV Grid with different Decimal Places based on Currency
    Regards,
    Dileep Kumar Reddy

  • Displayed nodes in a JTree

    Hi, i'm creating a JTree with TreeModel, and make the root as my c: drive. when the tree displayed, i found that it display some files that are actually not available in my c: drive. so, can anyone please tell me what's wrong in this case? thanks in advance!

    OK, these are two java files, please check for me. Thanks!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    public class MyTree extends JFrame implements ActionListener{
    File[] rt;
    File drive;
    private DefaultComboBoxModel comboModel;
    MyTreeModel model;
    File root = null;
    JTree tree;
        public MyTree() {
            initComponents();
    public void initComponents() {
    setLayout(new BorderLayout());
      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    panelB = new javax.swing.JPanel();
    panelB.setLayout(new BorderLayout());
    comboModel = new DefaultComboBoxModel();
    selectDrive = new JComboBox(comboModel);
    rt=File.listRoots();
      for (int i=0; i<rt.length; i++)
           drive = rt;
         comboModel.addElement(drive);
    selectDrive.setModel(comboModel);
    selectDrive.addActionListener(this);
    selectDrive.setActionCommand("sel_drive");
    tree = new JTree();
    tscrollPane = new JScrollPane(tree);
    displayTree();
    panelB.add(selectDrive,BorderLayout.NORTH);
    panelB.add(tscrollPane,BorderLayout.CENTER);
    add(panelB,BorderLayout.NORTH);
    pack();
    public void actionPerformed(ActionEvent e) {
         String cmd = e.getActionCommand();
         if(cmd.equals("sel_drive")){
                   displayTree();     
    public void displayTree(){
         Object obj = comboModel.getSelectedItem();
         String str = obj.toString();
         File f = new File(str);
         model = new MyTreeModel(f);
         tree.setModel(model);
    public static void main(String args[]){
         MyTree treefr = new MyTree();
         treefr.setSize(500, 500);
         treefr.setVisible(true);
    public JComboBox selectDrive;
    public JPanel panelB;
    public JScrollPane tscrollPane;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.io.*;
    class MyTreeModel implements TreeModel {
    public File root;
    public MyTreeModel(File rt) {
         root = rt;
    public Object getRoot() {
         return root;
    public boolean isLeaf(Object node) { 
         File leaf = (File)node;
         return leaf.isFile();      
    public int getChildCount(Object parent) {
         File p = (File)parent;
         if(p.isDirectory()){
              System.out.println("Total Files="+p.list().length);
              return p.list().length;
         }else{
              return 0;
    public Object getChild(Object parent, int index) {
    File p = (File)parent;
    String[] children = p.list();
    File child = new File(p,children[index]);
    try
         return child;
    catch (ArrayIndexOutOfBoundsException e)
    e.printStackTrace();
    return null;
    public int getIndexOfChild(Object parent, Object child) {
    String cname;
    String[] children = ((File)parent).list();
    if (children.length>0){
         cname = ((File)child).getName();
         for(int i = 0; i < children.length; i++) {
         if (cname.equals(children[i]))
              return i;
    else{
              return -1;
    return -1;
    public void valueForPathChanged(TreePath path, Object newvalue) {}
    public void addTreeModelListener(TreeModelListener l) {}
    public void removeTreeModelListener(TreeModelListener l) {}

  • N73 lockup with different icon

    I have recently had problems with my N73.  I keep getting a large icon, like a speech bubble with a phone symbol in it at the top of the screen which will not disappear.  This locks my phone up and the only way to get rid of it is to switch off and on.  Does anyone know what this icon means and how I can stop it happening.
    thanks

    I think the icon that you see at the top right corner of the screen is the same thing that you see after you pick up a call while you were doing something, like, typing a message, or viewing your gallery etc. In that case, there is/was a call in progress, or, in the process of getting disconnected.
    Sometimes, disconnecting a call can take very long, depending on the condition of your network. It can even result in your phone being non-responsive for quite some time. Therefore, try to reproduce the issue with a different network. Use a SIM from another network provider and check if you still have problems.
    Do you observe this problem without making or receiving a call? If so, then some installed application is making a call, and trying to do some mischief. Try to figure out which one. As a last resort, you should try uninstalling all the applications that you've installed, one by one, and see if the problem persists. A step higher, you can reset your phone in stages (soft reset, then, hard reset, and finally deep reset) and check if you still get the call indication and phone being non-responsive.
    Cheers,
    DeepestBlue
    5800 XpressMusic (Rock Stable) | N73 Music Edition (Never Say Die) | 1108 (Old and faithful)
    If you find any post useful, click on the Green "Kudos" Button on the left to say Thank You...

  • Greek Text Not Displaying Properly (Characters being replaced with different ones)

    Hi,
    I am using Adobe Photoshop CS3. I have a spreadsheet of Greek translations. When I copy and paste the text into Photoshop, certain characters are missed out or replaced with an incorrect one. I have tried downloading fonts that support the Greek character set, but still no luck. If I paste this text into any other applications (Word, explorer etc) the text displays properly. I was wandering if there is a setting or anything in photoshop that I need to change? It seems to be an issue with this application only.
    Many thanks,

    Have you tried to set your system language to a European setting, e.g. Ireland or UK? Seems like an issue with incorrect Unicode conversion. Also turn off OpenType features for automated glyph replacement in the menu of the Character palette...
    Mylenium

  • Ho to set different Icon for different Jtree Nodes dynamically??

    Dar Friends:
    I have following code.
    But if poosible I hope to:
    [1]. Dynamically assign or st each node with different Icons;
    [2]. these icons have different sizes, hope to resize them with same size, ie. 20X 20
    But try whole day, no idea how to to it,
    Can somebody throw a light??
    Thanks
    Good weekends
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    /** JTree with missing or custom icons at the tree nodes.
    *  1999 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    public class CustomIcons extends JFrame {
      public static void main(String[] args) {
        new CustomIcons();
      private Icon customOpenIcon = new ImageIcon("images/Circle_1.gif");
      private Icon customClosedIcon = new ImageIcon("images/Circle_2.gif");
      private Icon customLeafIcon = new ImageIcon("images/Circle_3.gif");
      public CustomIcons() {
        super("JTree Selections");
        Container content = getContentPane();
        content.setLayout(new FlowLayout());
        DefaultMutableTreeNode root =
          new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode child;
        DefaultMutableTreeNode grandChild;
        for(int childIndex=1; childIndex<4; childIndex++) {
          child = new DefaultMutableTreeNode("Child " + childIndex);
          root.add(child);
          for(int grandChildIndex=1; grandChildIndex<4; grandChildIndex++) {
            grandChild =
              new DefaultMutableTreeNode("Grandchild " + childIndex +
                                         "." + grandChildIndex);
            child.add(grandChild);
        JTree tree3 = new JTree(root);
        tree3.expandRow(3); // Expand children to illustrate leaf icons
        DefaultTreeCellRenderer renderer3 = new DefaultTreeCellRenderer();
        renderer3.setOpenIcon(customOpenIcon);
        renderer3.setClosedIcon(customClosedIcon);
        renderer3.setLeafIcon(customLeafIcon);
        tree3.setCellRenderer(renderer3);
        JScrollPane pane3 = new JScrollPane(tree3);
        pane3.setBorder(BorderFactory.createTitledBorder("Custom Icons"));
        content.add(pane3);
        pack();
        setVisible(true);
    }

    Thanks for your advice,I post my code as below, (I cannot post Max 5000, so post twice)
    [1]. main:
    import javax.swing.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.*;
    import java.awt.*;
         public class JTreeNew  extends JFrame {
           public JTreeNew() {
             super("Editable Tree Frame");
                JTreeSub js = new JTreeSub();
             setSize(200, 200);
            // WindowUtilities.setNativeLookAndFeel();
            // addWindowListener(new ExitListener());
             setDefaultCloseOperation(EXIT_ON_CLOSE);
           public class JTreeSub  extends JTree implements TreeSelectionListener{
                DefaultTreeModel treeModel;
                JTree tree;
                ContainerIconNode selectedNode;
                public JTreeSub() {
                super();
                init();
                public void init(){
                  ContainerIconNode Root = new ContainerIconNode("images/Root.GIF");
                  ContainerIconNode Animal = new ContainerIconNode("images/Animal.GIF");
                  ContainerIconNode Cat = new ContainerIconNode("images/Cat.GIF");
                  ContainerIconNode Fish = new ContainerIconNode("images/Fish.GIF");
                  ContainerIconNode GoldFish = new ContainerIconNode("images/GoldFish.GIF");
                  ContainerIconNode CatFish = new ContainerIconNode("images/CatFish.jpg");
                  ContainerIconNode Solomon = new ContainerIconNode("images/Solomon.GIF");
                  ContainerIconNode DogFish = new ContainerIconNode("images/DogFish.GIF");
                  ContainerIconNode Dog = new ContainerIconNode("images/Dog.jpg");
                  ContainerIconNode Mouse = new ContainerIconNode("images/Mouse.GIF");
                  ContainerIconNode Chicken = new ContainerIconNode("images/Chicken.GIF");
                  ContainerIconNode Pig = new ContainerIconNode("images/Pig.GIF");
                  treeModel = new DefaultTreeModel(Animal);
                  tree = new JTree(treeModel);
                  tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
                  ToolTipManager.sharedInstance().registerComponent(tree);
                  //Listen for when the selection changes.
                 tree.addTreeSelectionListener(this);
                  tree.setEditable(true);
                  treeModel.insertNodeInto(Animal,Root, 0);
                  Animal.add(Cat);
                  Animal.add(Fish);
                  Fish.add(GoldFish);
                  Fish.add(CatFish);
                  Fish.add(Solomon);
                  Fish.add(DogFish);
                  Animal.add(Dog);
                  Animal.add(Mouse);
                  Animal.add(Chicken);
                  Animal.add(Pig);
                  tree.expandRow(3); // Expand children to illustrate leaf icons
         //         DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
         //         renderer.setOpenIcon(Animal.getImageIcon());
         //         renderer.setClosedIcon(Dog.getImageIcon());
         //         renderer.setLeafIcon(CatFish.getImageIcon());
         //         tree.setCellRenderer(renderer);
                  ImageIcon startIcon = new ImageIcon("images/89.gif");
                  tree.setCellRenderer(new MyRenderer(startIcon));
                  getContentPane().add(tree, BorderLayout.CENTER);
              @Override
              public void valueChanged(TreeSelectionEvent e) {
                   selectedNode = (ContainerIconNode)
                                    tree.getLastSelectedPathComponent();
                 if (selectedNode == null) return;
                 Object nodeInfo = selectedNode.getUserObject();
                 if (selectedNode.isLeaf()) {
                      System.out.println("<JTreeNew> Node is  leaf=");
                 } else {
                      System.out.println("<JTreeNew> Node is  folder");
           private class MyRenderer extends DefaultTreeCellRenderer {
                 Icon nodeIcon;
                 public MyRenderer(ImageIcon icon) {
                      nodeIcon=icon;
                 public Component getTreeCellRendererComponent(
                                     JTree tree,
                                     Object value,
                                     boolean sel,
                                     boolean expanded,
                                     boolean leaf,
                                     int row,
                                     boolean hasFocus) {
    //                  System.out.println("<JTreeNew> Tree="+ tree);
    //                  System.out.println("<JTreeNew> nodeIcon="+ nodeIcon);
                      System.out.println("\n<JTreeNew> value="+ value);
                      System.out.println("<JTreeNew> sel="+ sel+"\n");
    //                  System.out.println("<JTreeNew> expanded="+ expanded);
    //                  System.out.println("<JTreeNew> leaf="+ leaf);
    //                  System.out.println("<JTreeNew> row="+ row);
    //                  System.out.println("<JTreeNew> hasFocus="+ hasFocus);
                     return this;
           public static void main(String args[]) {
                JTreeNew st = new JTreeNew();
                st.setVisible(true);
         }

  • In reports, i want to display currency field out put with diff currencies

    Hi all
    in reports, i want to display currency field out put with different type of currencies like 1st record in rupees 2nd record in dolors 3rd record in       
    Euros. for this i should not use any tables and any currency fields and any functional modules. pls give replay urgently.

    Hi swamy,
    so sorry, but you have to use some of the objects you do not want to:
    Currency values in ABAP are stored in currency fields (type CURR). If they are stored in structures or database, every CURR field must be connected to a CUKY field (currency key).
    Displaying data using WRITE statement four output on a list is obsolete technique, you may use the use WRITE with the option CURRENCY c to format according to currency c in table TCURX.
    SAP recommends to use ALV technique. If you use ALV to display structure data, then create a dictionary structure with currency value and currency key. The rest goes automatically.
    Believe me: It is much easier and more reliable.
    Regards,
    Clemens

  • Array of buttons with different boolean text ?

    I'm looking for a method of displaying a 2D button matrix with
    different boolean text on each button. It seems an array of booleans
    must all have the same text. Perhaps a cluster could be used, but the
    array makes button alignment easy and easy to determine which had been
    pressed (radiobutton style with only one button true at a time).
    Steve

    On 6 Dec 2002 05:31:21 -0800, [email protected] (humenik) wrote:
    >[email protected] (Steve Parus) wrote in message news:<[email protected]>...
    >> I'm looking for a method of displaying a 2D button matrix with
    >> different boolean text on each button. It seems an array of booleans
    >> must all have the same text. Perhaps a cluster could be used, but the
    >> array makes button alignment easy and easy to determine which had been
    >> pressed (radiobutton style with only one button true at a time).
    >It's easy to make them individuals in a cluster, and on the block
    >diagram use Cluster To Array to get it into array form for
    >manipulation. This can be superior to an array of buttons, not merely
    >because the buttons can thereby have differing colors and text. An
    >array of buttons cannot have the buttons Latched When Pressed; when in
    >a cluster, however, the latching action is available.
    When might that Latched When Pressed behavior be useful ? Using a 2D
    array of buttons (not cluster), in LV 6.1, a Value Changed event for
    the array can be used as you mention below to XOR the event's OldValue
    and NewValue and wire that to a local variable copy of the array.
    This easily gives a radio button effect for the entire 2D button
    matrix. The array control automatcially arranges the visual
    alignment of the buttons.
    For the cluster method, I'd like to programmatically change which
    button is true. All the approaches I come up with end up using
    Array-to-Cluster which then requires the cluster size to be specified.
    I may end up wanting to programmatically vary the number of buttons in
    both dimensions and hence the cluster size. LV's Align Objects and
    Distribue Objects ends up making the button visual alignment not
    difficult (for a 12 x 8 matrix).
    >Try this: take a cluster of four PB's (latched when pressed) put
    >inside a while loop. Initialize a boolean array of 4 to FALSE outside
    >the while loop, and attach it to a shift register input on the left
    >side of loop. Inside the loop, convert your cluster to an array. XOR
    >the shift register with this array from the buttons, and wire this to
    >the output shift register and to an indicator array. Set the boolean
    >to the loop so it will run free and start it up; on the control panel,
    >click on the PB's and you will see the outputs toggle.
    >
    >Greg

  • How to display different icon, for different node of jtree

    Hi All,
    How to display different icon, for different node of jtree

    you haven't responded to my last post here: [http://forums.sun.com/thread.jspa?threadID=5323190&messageID=10382676#10382676|http://forums.sun.com/thread.jspa?threadID=5323190&messageID=10382676#10382676]

  • How to Use different icons for JTree in the same level

    Hi guys, i come cross a problem with JTree. The module need a JTree which need to represent items in the same level using different icons. For example:
    [Icon for Root]Root
    |
    |_____________[Icon for Table] TABLES
    |
    |_____________[Icon for Index] INDEXS
    |
    |_____________[Icon for Views] VIEWS
    As i know, the default behavior for JTree is using the same icon for all leaves and
    the same icon for all node that has children. How can i achieve that?
    Thansk a lot!

    subclass DefaultTreeCellRenderer. if you overwrite the method below, then you can set the icon to whatever you want....!
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                    boolean sel,
                                    boolean expanded,
                                    boolean leaf, int row,
                                    boolean hasFocus) {
         String         stringValue = tree.convertValueToText(value, sel,
                               expanded, leaf, row, hasFocus);
            this.tree = tree;
         this.hasFocus = hasFocus;
         setText(stringValue);
         if(sel)
             setForeground(getTextSelectionColor());
         else
             setForeground(getTextNonSelectionColor());
         // There needs to be a way to specify disabled icons.
         if (!tree.isEnabled()) {
             setEnabled(false);
             if (leaf) {
              setDisabledIcon(getLeafIcon());
             } else if (expanded) {
              setDisabledIcon(getOpenIcon());
             } else {
              setDisabledIcon(getClosedIcon());
         else {
             setEnabled(true);
             if (leaf) {
              setIcon(getLeafIcon());
             } else if (expanded) {
              setIcon(getOpenIcon());
             } else {
              setIcon(getClosedIcon());
            setComponentOrientation(tree.getComponentOrientation());
         selected = sel;
         return this;
        }

  • How to display different icon within WDA alv table base on row data ?

    Hi,
    is that possible to display different icon for every row within ALV table depending on the row data ?
    for instance if the status 'S' display ~Icon/SuccessMessage and 'E' display ~Icon/ErrorMessage ?
    because base on this code below i only can set 1 icon for the whole row data.
    LOOP AT lt_columns ASSIGNING <fs_column>.
        CASE <fs_column>-id.
          WHEN 'ICO'.
            CREATE OBJECT lr_caption.
               lr_caption->set_image_source( value = '~Icon/SuccessMessage').
               <fs_column>-r_column->set_cell_editor( lr_caption ).
        ENDCASE.
      ENDLOOP.
    Thank you in advance.
    Fernand

    Hello,
    Yes it is possible to display different images based on data.
    For that what you can do is create one attribute 'STATUS' of type string in context node which you are mapping to ALV.
    And fill that attribute with the path to image based on your requirement like for status 'S' set the attribute to ~Icon/SuccessMessage and if status is 'E', set it to ~Icon/ErrorMessage at runtime.
    Now in the settings for ALV use the following code:
    * Display icon in column seatsocc
      DATA: lr_column TYPE REF TO cl_salv_wd_column,
            lr_image TYPE REF TO cl_salv_wd_uie_image,
            lv_icon TYPE string.
      lr_column = lv_model->if_salv_wd_column_settings~get_column( 'SEATSOCC' ).
      CREATE OBJECT lr_image.
      lr_image->SET_SOURCE_FIELDNAME( 'STATUS' ).
      lr_column->set_cell_editor( lr_image ).
    in the above code, column 'SEATSOCC' will be displayed as an icon.
    Sample code to fill the attribute 'STATUS'
    LOOP AT lt_flights INTO ls_flight.
        lv_seatsfree = ls_flight-seatsmax - ls_flight-seatsocc.
        IF lv_seatsfree = 0.
          ls_flight-status = 'ICON_RED_LIGHT'.
        ELSEIF lv_seatsfree <= 50.
          ls_flight-status = 'ICON_YELLOW_LIGHT'.
        ELSE.
          ls_flight-status = 'ICON_GREEN_LIGHT'.
        ENDIF.
        MODIFY lt_flights FROM ls_flight.
      ENDLOOP.
    Hope this helps!
    Regards,
    Srilatha
    Edited by: Srilatha M on Jun 25, 2010 12:02 PM

  • JTree Node Color, to distinguish between different activities

    Hi,
    Situation:          Dynamic JTree (Tree is constructed from as a result of Database). User has the option to either Enable / Disable node and can repeat the activities but restricted only one activity per node, the node is to be highlighted; to restrict the user from further activities.
    Problem:          Am a newbie to swing, after searching the forum for the same, i found few good solutions which are specific to color change of specific selected node, in a temporary context.
         But we need the node color change within a same level; to distinguish either the node is either enabled / disabled.
    Your help is appreciated,

    durino13 wrote:
    1. Is the approach above a good approach, how to load children 'lazilly'?Sounds pretty reasonable to me.
    2. I also use custom renderer to display different icons for every "tree" level. When I initially expand the 4th level, everything works fine !!! Then I collapse the 4th level and expand it again and here my problem starts: my 4th level icon is set to 'root level icon' instead of '4th level' icon. This does not happen, if computerNode.removeAllChildren(); method is removed from listening above
    Any idea, what am i doing wrong?Ummmm... Load the model the first time (only) the node is expanded... Putz!
    And I suggest you listen deeply to Mr Jacobs... He really does know what he's talking about ;-)
    ... and not this time, but in future: Swing questions are best asked in [THE Swing Forum|http://forums.sun.com/forum.jspa?forumID=57].
    Cheers. Keith.

  • Different Icon in a JTree

    Helle mates,
    is it possible to display different icons in a JTree?
    At present, I have the same folder-icons for all folders and the same leaf-icons for each leaf but I want different pics for each folder and for each folder different leaf-icons.
    Is that possible?
    I searched for it but nothing could help me so far. Hopefully, someone got an idea in here.
    Thank you so much

    you need a TreeCellRenderer. it will allow you to draw different icons for different nodes. for example like so:
    public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
      public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        Model model = (Model)((DefaultMutableTreeNode)value).getUserObject();
        setBackgroundNonSelectionColor(model.conditionColor());
        setBackgroundSelectionColor(model.conditionColor().darker());
        setOpenIcon(model.icon());
        setLeafIcon(model.icon());
        setClosedIcon(model.icon());
        Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        if (selected) setForeground(Color.white);
        return c;
    aJTree.setCellRenderer(new MyTreeCellRenderer());
    :thomas

  • How to change icon of a node or root node of a JTree

    i have a JTree with a root node, and leaf nodes. i want to change their icons. how can i do this?
    thanks

    Here's a search of the forums with the words 'tree', 'icon' and 'node' in the title
    http://onesearch.sun.com/search/developers/index.jsp?and=jtree+icon+node&nh=10&phr=&qt=&not=&field=title&since=&col=devforums&rf=0&Search.x=28&Search.y=15
    I looked at a couple and #5 seems interesting, but there are quite a few to choose from.

  • Problem inserting new node into JTree with depthFirstEnumeration()

    Hello,
    I'm currently trying to use depthFirstEnumeration() to add and delete nodes for a simple JTree. I've written a method to handle this, but it keeps coming back with an exception saying that 'new child is an ancestor'.
    All I'm trying to do is add and delete nodes from a JTree using add and remove buttons within a swing program. When a user adds the new node the JTree needs to be updated with new labels in sequential order dependent upon a depthFirst traversal of the JTree.
    My current code for the add button is as follows,
    public void actionPerformed(ActionEvent event) 
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            Enumeration e = rootNode.depthFirstEnumeration();
            if(event.getSource().equals(addButton))
                if (selectedNode != null)
                    while (e.hasMoreElements()) {
                    // add the new node as a child of a selected node at the end
                    DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)e.nextElement();
                     // treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    //System.out.print(newNode.getUserObject() + "" + newNodeSuffix++);
                    String label = "Node"+i;
                    treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    i++;
                      //make the node visible by scrolling to it
                    TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
                    TreePath path = new TreePath(totalNodes);
                    tree.scrollPathToVisible(path);
                    //System.out.println();
            else if(event.getSource().equals(deleteButton))
                //remove the selected node, except the parent node
                removeSelectedNode();           
        } As you can see in the above code, I've tested the incrementing of the new nodes in a System.out.print() statement and they appear to be incrementing correctly. I just can't see how to correctly output the labels for the nodes.
    Any help and advice always appreciated.

    This is about the 5th posting on the same question. Here is the link to the last posting so you can see what has already been suggested so you don't waste your time making the same suggestion.
    http://forum.java.sun.com/thread.jspa?threadID=704980
    The OP doesn't seem to understand that nodes don't just rename themselves and that renderers will only display the text of the current node. If you want the text displayed to changed, then you need to change the text associated with each node, which means iterating through the entire tree to update each node with new text. Then again, maybe I don't understand the question, but the OP keeps posting the same question without any additional information.

Maybe you are looking for

  • What is Material Requirement Planning

    what is Material Requirement Planning since i am a beginner in Supply chain management

  • OBIEE Basic Questions !!

    Hi All , I am new to OBIEE and comming from Business Objects background.I have following questions on each OBIEE tools .Really appreciate your answers Thanks Shivaji OBIEE Repository Qstns • If we change a table in DM (database) how do we refresh? If

  • Setting EXIF:GPSLatitude and EXIF:GPSLongitude from a PlugIn

    The new LR4 mapping faclity is great, but I'd like to map the locations on my existing photos (over 20,000).. All my photos already have city/country information set as Keywords, and I am able to separately convert these locations to GPS coordinates

  • Where are the finder preferences stored?

      I have an entry for a deleted folder in the "Places" section of the finder screen.  I am unable to remove it.  Rebooting doesn't help.

  • Rechargeable batteries for MUVO TX FM MP# PLA

    Hi everyone who reads this, Currently i am using Muvo TX FM mp3 player, I have been searching for rechargable batteriesfor so long tt i thought it is a easy job to find it, but i am wrong.... I hardly find it. So...can anyone who realli know which ki