Casting in JTree

I am trying to respong to a JTree selection. I have the following lines...
DefaultMutableTreeNode node = DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
Object nodeInfo = node.getUserObject();
I get an Exception when I try and cast the Object into something else...
URLElement ele = (URLElement) nodeInfo;
There are no errors during compilation, just at runtime, when I click on a node. Any ideas why there is a ClassCastException??
Thanks.

One trick that I use with JTree is to create a vector of the nodes I want to display.
I create my own class (usually subclassing an existing one) to add to the vector and add a toString() method to return the text to display in the tree. In this way you will be able to cast the object that you get back from JTree into the class that you require.

Similar Messages

  • Jtree casting problem

    Hi ,
    I am new to java swings, I am having problem with jtree casting.
    I have the tree which I created in the similar way as DNDTree
    The tree has 4 types such as model/subject/entity/attribues each
    of different class. My problem is when I drag and drop .. later I have
    to save the tree with all the properties into respective tables. Please
    help me how do I accomplish.
    Thanks

    Hi, This is the error I m getting.
    Excpetion is javax.swing.tree.DefaultMutableTreeNode cannot be cast to com.idecisions.cdi.hme_prac.MySubjectNodejava.lang.ClassCastException: javax.swing.tree.DefaultMutableTreeNode cannot be cast to com.idecisions.cdi.hme_prac.MySubjectNode
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • Casting JTree to JScrollPane

    Hi,
    Is this a reasonable thing to do? I'm debugging some code for a friend. The code was written by a third party who shall remain nameless. It reads a text file into a JTree structure and the casts it to a JScrollPane using "JScrollPane sp = (JScrollPane)srcList.getParent().getParent();". Is this reasonable?
    Secondly, in trying to debug this I'm trying to follow the execution thread into the JScrollPane object, however Eclipse reports that the line number is unavaiable, this to me looks like a version of the library with no debugging/symbol info but I can't find details of a version with debugging/symbol info.
    Apologies if these are dim questions, I'm still learning... I'm a masochist, I find debugging someone elses code is often the quickest way to learn a new programming language :-)
    Many thanks for any input anyone can give! I'm desperate on this.
    Cheers,
    Brian

    It is difficult to say what is reasonable without looking at the source code, but I consider it very unlikely that a sensibly designed program would guarantee that a JTree's parent's parent is always a JScrollPane. There are bound to be maintainability and reusability issues with implicit conditions like that.
    While Swing is not bug-free, I'd also guess that it is unnecessary for you to step through any JScrollPane code to find the bug you are looking for. Can you give a slightly more concrete example of what you're trying to diagnose?
    Some more information on debugging in the JRE applicable to Eclipse:
    http://developer.java.sun.com/developer/bugParade/bugs/4652184.html

  • When I chage node Name in jtree. It's casted String object

    Hello
    My English ability is very poor sorry
    now I make a tree
    and
    jtree.setEditable(true);
    I change my tree node's value
    from
    -root
    |-Hello
    to
    -root
    |-Hi
    after I chaged the value
    the value's class type is String
    I wan't to same class before change.
    How can I do?
    thank you

    Hi! Take a look at treeCellEditors in Java Tutorial. You need to provide custom TreeCellEditor.
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • JTree data object type casting

    I need to invoke a method on my data object after the user selects the corresponding node on the tree. I'm not able to type cast the DefaultMutableTreeNode to my class called Account. I've even tried extending DefaultMutableTreeNode in my class Account but of no avail.
    any help in this matter will be highly appreciated
    thanx
    seeta

    Are you talking about the user object that is passed in the constructor of DefaultMutableTreeNode?
    If so, you don't cast the node itself, you get the user object and cast that (i.e. getUserObject()).

  • How do I use JPanel as a leaf in JTree ?

    Hi All,
    I am a bit of a newbie and I've been trying to change the behavior of my application.
    I have a JTree that I now want to change the rendering of a leaf to be a JPanel. The JPanel will have a couple of JButtons and some text and the user can interact with the JButtons. I was successful in creating the JPanel, adding the buttons and then making my own TreeCellRenderer. Everything displays fine, but the user can not interact with the JButtons, whenever I click on a button in the leaf, the whole leaf is highlighted - I suppose I should not be surprised because this is probably behaving just a cell in a JTree should.
    So I searched the forums and used Google and have found several examples of people using JCheckBox as nodes/leaf(s) in a JTree but none with a JPanel as a leaf. I took one of the check box demos from here ( [http://www.coderanch.com/t/330630/Swing-AWT-SWT-JFace/java/add-swing-component-tree]) and then hacked it a bit but am stuck with the following error :
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.JPanel
    which is pointing to the line with JPanel temp2 = (JPanel) temp.getUserObject();
    Does anyone have either some code or suggestions to accomplish a leaf as a JPanel with some buttons ?
    Thanks in advance !
    import javax.swing.*;*
    *import javax.swing.tree.*;
    import java.awt.event.*;*
    *import java.awt.*;
    public class treedemo1 extends JFrame {
        public treedemo1() {
            super("TreeDemo");
            setSize(1500, 1500);
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            customLeafPanel cp1 = new customLeafPanel();
            customLeafPanel cp2 = new customLeafPanel();
            customLeafPanel cp3 = new customLeafPanel();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Query Results");
            DefaultMutableTreeNode n1 = new DefaultMutableTreeNode(cp1, false);
            DefaultMutableTreeNode n2 = new DefaultMutableTreeNode(cp2, false);
            DefaultMutableTreeNode n3 = new DefaultMutableTreeNode(cp3, false);
            root.add(n1);
            root.add(n2);
            root.add(n3);
            JTree tree = new JTree(root);
            p.add(tree, BorderLayout.NORTH);
            getContentPane().add(p);
            TestRenderer tr = new TestRenderer();
            tree.setEditable(false);
            tree.setCellRenderer(tr);
        public class customLeafPanel extends JPanel {
            public customLeafPanel() {
                JPanel clpPanel = new JPanel();
                JButton helloJButton = new JButton("Hello");
                this.add(helloJButton);
        public class TestRenderer implements TreeCellRenderer {
            transient protected Icon closedIcon;
            transient protected Icon openIcon;
            public TestRenderer() {
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value,
                    boolean selected,
                    boolean expanded,
                    boolean leaf,
                    int row,
                    boolean hasFocus) {
                DefaultMutableTreeNode temp = (DefaultMutableTreeNode) value;
                JPanel temp2 = (JPanel) temp.getUserObject();
                return temp2;
            public void setClosedIcon(Icon newIcon) {
                closedIcon = newIcon;
            public void setOpenIcon(Icon newIcon) {
                openIcon = newIcon;
        public static void main(String args[]) {
            JFrame frame = new treedemo1();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

    Thank you TBM and DB for your replies ! Adding TBM's code does indeed fix the JPanel issue and as TBM indicated this does not actually solve my ultimate problem (Can I give you each 1/2 the Duke points?)
    As a newbie, I am still learning and DB pointed out that "You can however interact with an editor". So after reading the suggested tutorials and looking back at the example code that I hacked. I added the cellEditor back in and it WORKS ! Its funny, I deleted that bits of code from the example, assuming the cellEditor allows you to "edit" (ie change), not interact with it (symantics I guess)
    Thanks again guys for pointing this newbie in the right direction. Frankly I am somewhat surprised that I could finally begin to read and understand what the tutorial and suggestions are telling me ! What is one step up from a newbie ?
    unfortunately I can not post the code because the length of the message is > 5000 :(

  • Help with displaying a JTree

    Hi,
    I have developed a webspider that cycles through a website detecting all urls and checking for borken links. I currently have build a JTree that takes the current url that is being processed and creates a string and adds it to a JTree. The problem I have is that the urls are printed in the JTree as one long list, e.g.
    |Test
    |____url 1
    |____url 1a
    |____url 2
    |____url 2a
    I would like it to disply like this:
    |Test
    |____url 1
    |-------|____url 1a
    |____url 2
    |-------|____url 2a
    (I have had to place the dashes in so it displays properly)
    So that the strucutre of the website can be seen. I have read the JTree tutroial and my code looks like this, sorry its large i'm not too sure which bits to cut out:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class gui extends JFrame implements Runnable
          *declare variable, boolean
          *thread, a object and a center
          *pane
         protected URL urlInput;
         protected Thread bgThread;
         protected boolean run = false;
         protected WebSpider webSpider;
         public String brokenUrl;
         public String goodUrl;
         public String deadUrl;
         protected DefaultMutableTreeNode rootNode;
        protected DefaultTreeModel treeModel;
         public gui()
                *create the gui here
               setTitle("Testing Tool");
             setSize(600,600);
             //add Buttons to the tool bar
             start.setText("Start");
             start.setActionCommand("Start");
             toolBar.add(start);
             ButtonListener startListener = new ButtonListener();
                 start.addActionListener(startListener);
              cancel.setText("Cancel");
             cancel.setActionCommand("Cancel");
             toolBar.add(cancel);
             ButtonListener cancelListener = new ButtonListener();
                 cancel.addActionListener(cancelListener);
                 clear.setText("Clear");
             clear.setActionCommand("Clear");
             toolBar.add(clear);
             ButtonListener clearListener = new ButtonListener();
                 clear.addActionListener(clearListener);
                 close.setText("Close");
             close.setActionCommand("Close");
             toolBar.add(close);
             ButtonListener closeListener = new ButtonListener();
                 close.addActionListener(closeListener);
                 //creat a simple form
                 urlLabel.setText("Enter URL:");
                 urlLabel.setBounds(100,36,288,24);
                 formTab.add(urlLabel);
                 url.setBounds(170,36,288,24);
                 formTab.add(url);
                 current.setText("Currently Processing: ");
                 current.setBounds(100,80,288,24);
                 formTab.add(current);
             //add the scrol pane and text area to the error tab
             errorTab.add(errorPane);
             errorPane.setBounds(0,0,580,490);
             errorPane.getViewport().add(errorText);
             //add the scroll pane to the tree tab
             treeTab.add(treePane);
             treePane.setBounds(0,0,580,490);
             //create the JTree
             rootNode = new DefaultMutableTreeNode("Test");
             treeModel = new DefaultTreeModel(rootNode);
             treeModel.addTreeModelListener(new MyTreeModelListener());
             tree = new JTree(treeModel);
             tree.setEditable(true);
             tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
             treePane.getViewport().add(tree);
             //create the tabbed window             
            centerPane.setBorder(new javax.swing.border.EtchedBorder());
            formTab.setLayout(null);
            errorTab.setLayout(null);
            treeTab.setLayout(null);
            centerPane.addTab("Search Parameters", formTab);
            centerPane.addTab("Error Messages", errorTab);
            centerPane.addTab("Website Structure", treeTab);
              //add the tool bar and tabbed pane
              getContentPane().add(toolBar, java.awt.BorderLayout.NORTH);
            getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);             
                 *create the tool bar pane, a center pane, add the buttons,
                 *labels, tabs, a text field for user input here
                javax.swing.JPanel toolBar = new javax.swing.JPanel();
                javax.swing.JButton start = new javax.swing.JButton();
              javax.swing.JButton cancel = new javax.swing.JButton();
              javax.swing.JButton clear = new javax.swing.JButton();
              javax.swing.JButton close = new javax.swing.JButton();      
                javax.swing.JTabbedPane centerPane = new javax.swing.JTabbedPane();
                javax.swing.JPanel formTab = new javax.swing.JPanel();
                javax.swing.JLabel urlLabel = new javax.swing.JLabel();
                javax.swing.JLabel current = new javax.swing.JLabel();
                javax.swing.JTextField url = new javax.swing.JTextField();
                javax.swing.JPanel errorTab = new javax.swing.JPanel();
                javax.swing.JTextArea errorText = new javax.swing.JTextArea();
                javax.swing.JScrollPane errorPane = new javax.swing.JScrollPane();
                javax.swing.JPanel treeTab = new javax.swing.JPanel();
                javax.swing.JScrollPane treePane = new javax.swing.JScrollPane();
                javax.swing.JTree tree = new javax.swing.JTree();
               *show the gui
              public static void main(String args[])
                  (new gui()).setVisible(true);
              *listen for the button presses and set the
              *boolean flag depending on which button is pressed
             class ButtonListener implements ActionListener
                  public void actionPerformed(ActionEvent event)
                       Object object = event.getSource();
                       if (object == start)
                            run = true;
                            startActionPerformed(event);
                       if (object == cancel)
                            run = false;
                            startActionPerformed(event);
                       if (object == clear)
                            errorText.setText("");
                            rootNode.removeAllChildren();
                           treeModel.reload();
                       if (object == close)
                            System.exit(0);
              *this method is called when the start or
              *cancel button is pressed.
             void startActionPerformed (ActionEvent event)
                  if (run == true && bgThread == null)
                       bgThread = new Thread(this);
                       bgThread.start();
                  if (run == false && bgThread != null)
                       webSpider.cancel();
              *this mehtod will start the background thred.
              *the background thread is required so that the
              *GUI is still displayed
             public void run()
                  try
                           webSpider = new WebSpider(this);
                         webSpider.clear();
                         urlInput = new URL(url.getText());
                       webSpider.addURL(urlInput);
                       webSpider.run();
                       bgThread = null;
                      catch (MalformedURLException e)
                           addressError addErr = new addressError();
                         addErr.addMsg = "URL ERROR - PLEASE CHECK";
                         SwingUtilities.invokeLater(addErr);
                 *this method is called by the web spider
                 *once a url is found. Validation of navigation
                 *happens here.
                public boolean urlFound(URL urlInput,URL url)
                      CurrentlyProcessing pro = new CurrentlyProcessing();
                  pro.msg = url.toString();
                  SwingUtilities.invokeLater(pro);
                  if (!testLink(url))
                        navigationError navErr = new navigationError();
                        navErr.navMsg = "Broken Link "+url+" caused on "+urlInput+"\n";
                        brokenUrl = url.toString();
                        return false;
                  if (!url.getHost().equalsIgnoreCase(urlInput.getHost()))
                        return false;
                  else
                         return true;
                //this method is returned if there is no link on a web page
                public void urlNotFound(URL urlInput)
                          deadEnd dEnd = new deadEnd();
                           dEnd.dEMsg = "No links on "+urlInput+"\n";
                           deadUrl = urlInput.toString();                
                //this method is called internally to check that a link works              
                protected boolean testLink(URL url)
                   try
                         URLConnection connection = url.openConnection();
                         connection.connect();
                         goodUrl = url.toString();
                         return true;
                  catch (IOException e)
                         return false;
                //this method is called when an error is found            
                public void urlError(URL url)
              //this method is called when an email address is found             
                public void emailFound(String email)
              //this method will update any navigation errors found
              class addressError implements Runnable
                   public String addMsg;
                   public void run()
                        current.setText("Currently Processing: "+ addMsg);
                        errorText.append(addMsg);
              class navigationError implements Runnable
                   public String navMsg;
                   public void run()
                        errorText.append(navMsg);
              class deadEnd implements Runnable
                   public String dEMsg;
                   public void run()
                        errorText.append(dEMsg);
              //this method will update the currently processing field on the GUI
              public class CurrentlyProcessing implements Runnable
                   public String msg;
                  //public String msgInfo = msg;
                     public void run()
                         current.setText("Currently Processing: " + msg );
                         addObject(msg);
             //add a node to the tree
                public DefaultMutableTreeNode addObject (Object child)
                 DefaultMutableTreeNode parentNode = null;
                 return addObject(parentNode, child, true);
             public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,Object child,boolean shouldBeVisible)
                 DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
                 if (parent == null)
                     parent = rootNode;
                 treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
                 if (shouldBeVisible)
                     tree.scrollPathToVisible(new TreePath(childNode.getPath()));
                      return childNode;
             //listener for the tree model     
             public class MyTreeModelListener implements TreeModelListener
                  public void treeNodesChanged (TreeModelEvent e)
                       DefaultMutableTreeNode node;
                       node = (DefaultMutableTreeNode)
                       (e.getTreePath().getLastPathComponent());
                       try
                            int index = e.getChildIndices()[0];
                            node = (DefaultMutableTreeNode)
                            (node.getChildAt(index));
                       catch (NullPointerException exc)
                  public void treeNodesInserted(TreeModelEvent e)
                  public void treeStructureChanged(TreeModelEvent e)
                  public void treeNodesRemoved(TreeModelEvent e)
    }It uses a class called webspider which i have not attached, if required please let me know. I beleive that in addObject I am adding all nodes to the root as children.
    Any help would be much appreciated.
    Many Thanks
    MRv

    I would recomend you create your own JTree class for this.
    Here are a few things I set in my constructor within the JTree:
    // turn on tooltips
    ToolTipManager.sharedInstance().registerComponent(this);
    // used by two setters so create reference
    RollupTreeCellRenderer renderer = new RollupTreeCellRenderer();
    // customizing the icons for the tree
    // setting the folder icons
    renderer.setOpenIcon(IconLoader.getIcon("Open.gif"));
    renderer.setClosedIcon(IconLoader.getIcon("Folder.gif"));
    // inventory icon
    renderer.setLeafIcon(IconLoader.getIcon("Document.gif"));
    // add renderer to highlight Inventory nodes with Red or Blue text
    setCellRenderer(renderer);
    Here is the renderer class example:
    class RollupTreeCellRenderer
    extends DefaultTreeCellRenderer
    * Configures the renderer based on the passed in components.
    * The value is set from messaging the tree with
    * <code>convertValueToText</code>, which ultimately invokes
    * <code>toString</code> on <code>value</code>.
    * The foreground color is set based on the selection and the icon
    * is set based on on leaf and expanded.
    * @param tree JTree
    * @param value Object
    * @param sel boolean
    * @param expanded boolean
    * @param leaf boolean
    * @param row int
    * @param hasFocus boolean
    * @return Component
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean sel,
    boolean expanded,
    boolean leaf, int row,
    boolean hasFocus)
    // call super for default behavior
    super.getTreeCellRendererComponent(tree,
    value,
    sel,
    expanded,
    leaf,
    row,
    hasFocus);
    // if the current node is selected do NOT over-ride
    // the default colors
    if (sel)
    return this;
    // cast to our wrapper Node class
    RollupNode node = (RollupNode) value;
    if (node.isInventory())
    if (RollupMediator.getInstance().nodeInList(node))
    setForeground(RollupTree.FOUND);
    setToolTipText("Click to find positions count");
    else
    setForeground(RollupTree.NOT_FOUND);
    setToolTipText("Inventory not in current business date");
    else
    setToolTipText("Double click to edit name");
    return this;
    } // Renderer
    Let me know if you need more examples.
    BTW
    I the TreeCellRenderer example is not public so I can add it to the bottom of the file that contains my custom JTree.

  • Using a JTree as an explorer

    Hi all of you there!
    I made a JTree from my local disk (c:/) en in that JTree I can navigate through al the folders of my C-disk.
    Now I want to have the directory of the file that is highlighted. I already try lot of things but no one work.
    The best thing I get was: "nodeinfo = [Ljavax.swing.tree.TreeNode;@110c31"
    {code}
         private JScrollPane getFileScrollPane(String file) {
    if (fileScrollPane == null) {
                   fileScrollPane = new JScrollPane();
                   fileScrollPane.setPreferredSize(new Dimension(200, 400));
              File root;
              FileTreeModel model;
              //JTree tree;
                   root = (new File(file));
         model = (new FileTreeModel(root));
         tree = new JTree();
         tree.setModel(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.addTreeSelectionListener(tree);
                   tree.addTreeSelectionListener(new TreeSelectionListener() {
                   public void valueChanged(TreeSelectionEvent e) {
                        DefaultMutableTreeNode node = new DefaultMutableTreeNode();
    tree.getLastSelectedPathComponent();
                        /* if nothing is selected */
                   if (node == null)
                        return;
                   /* retrieve the node that was selected */*
                   Object nodeInfo = node.getPath();
                   //Object nodeInfo = node.getUserObject();
                   System.out.println("nodeinfo = " + nodeInfo);
                   System.out.println("root=" + node.getParent());
         fileScrollPane = new JScrollPane(tree);
         fileScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
         fileScrollPane.setPreferredSize(new Dimension(315, 300));
              return fileScrollPane;
         }{code}
    the String file contains "c:/"
    I hope that someone can help me

    Hi, thanks for your help!
    But it won't work.
    Now I get the following error: (I paste everything in here, maybe someone wants to see it all)
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.io.File cannot be cast to javax.swing.tree.DefaultMutableTreeNode
         at main.Main$10.valueChanged(Main.java:553)
         at javax.swing.JTree.fireValueChanged(Unknown Source)
         at javax.swing.JTree$TreeSelectionRedirector.valueChanged(Unknown Source)
         at javax.swing.tree.DefaultTreeSelectionModel.fireValueChanged(Unknown Source)
         at javax.swing.tree.DefaultTreeSelectionModel.notifyPathChange(Unknown Source)
         at javax.swing.tree.DefaultTreeSelectionModel.setSelectionPaths(Unknown Source)
         at javax.swing.tree.DefaultTreeSelectionModel.setSelectionPath(Unknown Source)
         at javax.swing.JTree.setSelectionPath(Unknown Source)
         at javax.swing.plaf.basic.BasicTreeUI.selectPathForEvent(Unknown Source)
         at javax.swing.plaf.basic.BasicTreeUI$Handler.handleSelection(Unknown Source)
         at javax.swing.plaf.basic.BasicTreeUI$Handler.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • About a JTree of mixed String and JLabel leafs

    Dear Java and Swing freaks,
    Why do I get the text code instead of the expected JLabel in the leaves of my JTree ?
    I want to construct a Jtree in which each tree leaf is made of a JLabel (displaying an amount and with a coloured background), followed by a normal String (the label of this amount).
    An array (of arrays) of Ojects describes the tree that I want to display in a Swing JPanel of Container, as in the "2.1 Simple JTREE Example" at URL
    http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JTree.html
    So, using the "DefaultMutableTreeNode" class and a "private DefaultMutableTreeNode processHierarchy(Object[] hierarchy)" re-entering function.
    Either the 'nodeSpecifier' is of type 'new Object[]', and the 'processHierarchy()' interpretes it as a new node,
    Or the 'nodeSpecifier' is of type 'JLabel' (or 'String'), and the 'processHierarchy()' has to interprete it as a new leaf.
    Of course, 'JLabel', as 'String', is also a subclass of 'Object'.
            BigDecimal TotalDistrNetBeh1= 1.11;
            Object[] hi�rarchie =
            { "Blablabla",
              new Object[]
              { "Bloc de compteurs",
                new Object[] { "Total1" + " : The 1st listed item = The title of this node",
                                     new JLabel(TotalDistrNetBeh1.toPlainString()),
                       /* + "DistrNetBeh1" */
                                     new JLabel(" 2.22")
                       /* + "DistrNetBeh2" */
                new Object[] { "Total2" + " : Title of this node",
                                     new JLabel("Total Bijdrage Herniewbare energie"),
                   /* Test : Leaf of type 'String' mixed with leaves of type 'JLabel'.
                                     "Total Opties : French and Dutch",
                                     "<html>Total Bijdrage <font color=red>WarmteKrachtKoppeling</font></html>",
                                     TotalDistrNetBeh1.toPlainString() + "Test1",
                                     new JLabel("<html>Total <font color=blue>Test2</font></html>")
            };In the displayed tree, rows with JPanel appear like this :
    javax.swing.JLabel[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=8388608,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text= 2.22,verticalAlignment=CENTER,verticalTextPosition=CENTER]
    <b>instead of simply " 2.22"</b>, as if there is a hiden (java.lang.String) casting. Why ?
    Nevertheless, the 'nodeSpecifier' argument in
            else
              child = new DefaultMutableTreeNode(nodeSpecifier); // Leafis casted to (javax.swing.JLabel)
    and 'child' and 'node' - both of 'Object' type - seem to be casted to (javax.swing.tree.DefaultMutableTreeNode)
    For memo :
        private DefaultMutableTreeNode constructHi�rarch(Object[] hi�rarchie)
        { DefaultMutableTreeNode node = new DefaultMutableTreeNode(hi�rarchie[0]);
          DefaultMutableTreeNode child;
          for(int i=1; i<hi�rarchie.length; i++)
          { Object nodeSpecifier = hi�rarchie;
    if (nodeSpecifier instanceof Object[]) // Node with children
    // Re-entering the function
    child = constructHi�rarch((Object[])nodeSpecifier);
    else
    child = new DefaultMutableTreeNode(nodeSpecifier); // Leaf
    node.add(child);
    return(node);
    Is it "DefaultMutableTreeNode(nodeSpecifier)" or "add(child)" that cannot operate properly with a argument of type 'JLabel' ?
    How to solve it ?
    Sorry, I'm a beginner in Java and Swing.
    Thanks in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Learn to properly use a TreeCellRenderer
    You never need to add a Component to a JTree, ie JLabel. You add the data, like a String, and then render the component you want to appear. Already, the String you have in your JTree are being rendered using JLabels, with a White Background. Hence, you need to provide a custom renderer that allows you to display different coloured rows depending on your condition or requirements.
    Read a little more on the TreeCellRenderer here: http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    ICE

  • DefaultMutableTreeModel, and casting TreeModel - DefaultMutableTreeModel

    I have a workflow object, from which I create a workflowTreeModel and display this in a JTree - all works OK....
    I now need to create a DefaultMutableTreeModel from the same workflow object and I in need of some pointers. (please)
    All the examples I can find create a number of DefaultMutableTreeNodes (eg, red, blue, green) and add them to a DefaultMutableTreeNode (eg.color)...
    As I already have a workflow object that I am trying to display this approach doesn't fit. Is there anyway to create a DefaultMutableTreeModel in the same way as I am creating the TreeModel?
    Looking at the 'understanding the treeModel' tutorial from Sun I see that I should be able to cast my workflowTreeModel to a DefaultTreeModel using:
    JTree() myTree = new JTree(workflowTreeModel);
    DefaultTreeModel t = (DefaultTreeModel) myTree.getModel();
    However I get a class cast exception trying to do this - I imagine this is as a result of the way the workflowTreeModel is created (code below).
    If anyone can show me the correct way to create a DefaultTreeModel from my workflow object I would be grateful....
    (workflowTreeModel code: )
    public class WorkflowTreeModel extends AbstractWorkflowTreeModel {
         * Commons Logger for this class
        private static final Log logger = LogFactory.getLog(WorkflowTreeModel.class);
        private Workflow rootWorkflow;     
         public WorkflowTreeModel(Workflow root) {
              rootWorkflow = root;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getRoot()
         public Object getRoot() {
              return rootWorkflow.getSequence();
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getChildCount(java.lang.Object)
         public int getChildCount(Object parent) {
              int i = 0;
              if(parent instanceof Workflow) {
                   i = 1;
              else if(parent instanceof Sequence) {
                   Sequence s = (Sequence)parent;
                   i = s.getActivityCount();
              else if(parent instanceof Flow) {
                   Flow f = (Flow)parent;
                   i = f.getActivityCount();
              else if(parent instanceof For) {
                   For f = (For)parent;
                   Sequence s = (Sequence)f.getActivity();
                   i = s.getActivityCount();
              else if (parent instanceof If) {
                   If a = (If)parent;
                   if (a.getElse() != null && a.getElse() instanceof Else)
                        i = i + 1;
                   if (a.getThen() != null && a.getThen() instanceof Then)
                        i = i + 1;
              else if (parent instanceof Else || parent instanceof Then) {
                 i = 1;
              else if (parent instanceof For || parent instanceof Parfor || parent instanceof While) {
                   i = 1;
              else if (parent instanceof Scope) {
                   i = 1;
              else if (parent instanceof Script) {
                   i = 1;
              return i;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#isLeaf(java.lang.Object)
         public boolean isLeaf(Object node) {
              boolean b = true;
              if (node instanceof Sequence) {
                   if (((Sequence)node).getActivityCount() > 0)
                        b = false;
              if (node instanceof Flow) {
                   if (((Flow)node).getActivityCount() > 0)
                       b = false;
              else if (node instanceof If || node instanceof Else || node instanceof Then) {
                   b = false;
              else if (node instanceof For || node instanceof Parfor || node instanceof While) {
                   b = false;
              else if (node instanceof Scope) {
                   b = false;
              else if (node instanceof Workflow) {
                   b = false;
              else if (node instanceof Script) {
                   b = false;
              return b;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#addTreeModelListener(javax.swing.event.TreeModelListener)
         public void addTreeModelListener(TreeModelListener l) {
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#removeTreeModelListener(javax.swing.event.TreeModelListener)
         public void removeTreeModelListener(TreeModelListener l) {
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getChild(java.lang.Object, int)
         public Object getChild(Object parent, int index) {
              Object ob = null;
              if (parent instanceof Workflow){
                   Workflow w = (Workflow)parent;
                   ob = w.getSequence();
              else if(parent instanceof Sequence) {
                   Sequence s = (Sequence)parent;
                   ob = s.getActivity(index);
              else if(parent instanceof Flow) {
                   Flow f = (Flow)parent;
                   ob = f.getActivity(index);
              else if (parent instanceof For) {
                   For f = (For)parent;
                   Sequence s = (Sequence)f.getActivity();
                   ob = s.getActivity(index);
              else if (parent instanceof Parfor) {
                   Parfor p = (Parfor)parent;
                   ob = p.getActivity();
              else if (parent instanceof Scope) {
                   Scope s = (Scope)parent;
                   ob = s.getActivity();
              else if (parent instanceof While) {
                   While w = (While)parent;
                   ob = w.getActivity();
              else if (parent instanceof If) {
                   If i = (If)parent;
                   if (index == 0) {
                        if ((i.getThen() != null) && (i.getThen() instanceof Then)){
                             ob = i.getThen();
                        else if ((i.getElse() != null) && (i.getElse() instanceof Else)){
                             ob = i.getElse();
                   if (index == 1) {
                        if ((i.getElse() != null) && (i.getElse() instanceof Else)){
                             ob = i.getElse();
                        else if ((i.getThen() != null) && (i.getThen() instanceof Then)){
                             ob = i.getThen();
              else if (parent instanceof Else) {
                   Else e = (Else)parent;               
                   ob = e.getActivity();               
              else if (parent instanceof Then) {
                   Then t = (Then)parent;               
                   ob = t.getActivity();               
              else if (parent instanceof Script) {
                   Script s = (Script)parent;
                   ob = s.getBody();
              return ob;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getIndexOfChild(java.lang.Object, java.lang.Object)
         public int getIndexOfChild(Object parent, Object child) {
              logger.debug("getIndexOfChild");
              // TODO Auto-generated method stub
              return -1;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#valueForPathChanged(javax.swing.tree.TreePath, java.lang.Object)
         public void valueForPathChanged(TreePath path, Object newValue) {
              // TODO Auto-generated method stub
    public abstract class AbstractWorkflowTreeModel extends WorkflowTreeModelSupport implements TreeModel {
    }

    JTree() myTree = new JTree(workflowTreeModel);
    DefaultTreeModel t = (DefaultTreeModel) myTree.getModel();the only way you can cast this is that workflowTreeModel must extends DefaultTreeModel
    What you can do is to for WorkFlowTreeMdeol to extends DefaultTreeModel
    or case it to WorkFlowTreeModel
    JTree() myTree = new JTree(workflowTreeModel);
    WorkFlowTreeModel model = (WorkFlowTreeModel) myTree.getModel();

  • Customizing JTree Nodes ImageIcons???

    I have a JTree. Iam trying to customize the icons of it instead of the defaulticons available for leaf and branch nodes.I successfully set a new icon for leaf nodes by calling setLeafIcon.Also i can use setOpenIcon and setClosedIcon for the expanded and closed branches.
    But in my application when my GUI is launched i actually set the JTree in its fully expansion form.
    so there is no difference between setOpenICon and setClosedIcon as all of them are expanded.so how do i differentiate between the two and set different icons for both of them.
    exmaple:Cricket club is my root node..I have for ex:ABC , BCD, and CDE club underneath that(branch nodes).Under each club i have player1,player2, player3. .etc..so i want to set 3 different icons,,one for cricket club, 2nd for ABC,BCD andCDE clubs and 3rd one for players.since my JTree is expanded the same icon is set for CricketClub(root Node) and ABC,BCD and CDE club(branch nodes)..How can iset different icons to these. can anyone help me on this..I am sort of new to JTree.So code snippet will be a welcome..
    Thanks Much in advance

    To fully expand the tree, use the method scrollPathToVisible(TreePath path). The path is the path for your tree's last node. The DefaultMutableTreeNode class should have some methods to find the path for a particular node.
    To set the icons for a particular node, depending on their opened or closed state, Make a subclass of TreeCellRenderer. If you look at the API for TreeCellRenderer, you will see that it will tell you if the current node is expanded, selected, leaf, hasfocus, etc...
    If you want to set an open icon for an expanded node, just check if it is expanded. Cast the Object value to a DefaultMutableTreeNode and set the Icon for it, unless you have your own class for your nodes. Lastly, set your renderer for your JTree with setCellRenderer(TreeCellRenderer ren). I hope this helps.

  • JTree custom DefaultTreeCellRenderer with custom DefaultMutableTreeNode

    Is there a way to create my own version of DefaultTreeCellRenderer that does not use DefaultMutableTreeNode? I tried copying an example of a custom DefaultTreeCellRenderer but I can’t cast the "value" in getTreeCellRendererComponent() to my own version of DefaultMutableTreeNode.
    From the looks of the documentation below shouldn't I be able to do that?
    Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)

    oops,
    I found out why. I created my custom DefaultTreeCellRenderer before I populated the root node with my DefaultMutableTreeNode. So I guess, java went with the default. When I created my custom DefaultTreeCellRenderer after I populated the root node, everything worked.

  • Avoiding duplicates in JTree

    I am trying to avoid duplicates in a JTree and don't think I should have to loop through all the objects and compare them for every new entry. I would like find a way to compare the label of an existing object with the one I'm about to add to the tree.
    I'm trying to use getIndexOfChild method instead of looping. The method as it is now is doesn't work. I've tried type casting and toString, but haven't found the correct combo.
    Thanks....
    public void refreshHostTree(JTree mytree, ArrayList myhostnodes) {
    // duplicates have already been accounted for
    // when the host list was built.
    DefaultTreeModel mymodel = (DefaultTreeModel)mytree.getModel();
    Object myroot = mymodel.getRoot();
    System.out.println("root is "+myroot);
                   for (int i=0; i < myhostnodes.size(); i++) {                      
    // update with new node
    DefaultMutableTreeNode curnode = new DefaultMutableTreeNode(myhostnodes.get(i));
    if((mymodel.getIndexOfChild(myroot,curnode) < 0 )) {
    System.out.println("object to add is "+curnode);
    mymodel.insertNodeInto(curnode,(DefaultMutableTreeNode)myroot,0);
    }

    I looked through many posts before posting this question. Could you send me a reference or what u searched on?
    As for your questions......
    1. Can unique nodes be duplicated in other nodes of the tree?
    - yes and no. No for the tree I'm working on now, yes for the tree on the next tabbedpane I'm populating.
    1.a If yes, can a node be a child of itself?
    - no. I don't want it to be at least...
    2. How many nodes total in the tree?
    - for my project, maximum of 500. Probably will put them in a paged scroll pane.
    3. How many average children does a node have?
    - depends on how young the sampled group started having children????
    3.a What is the maximum number of children a node can have?
    - I'm sure my 500 is below the limit, but only testing will tell.
    4. Once the tree is built is it static?
    - no. It doesn't have to be. There are good examples of this.
    5. How slow is too slow?
    - real time is a relative term! I'm trying to be more efficient with doing it this way instead of looping through all the nodes of the tree. I'm also hard headed and think that there should be an easy way to do this.
    Thanks

  • How remove (or change) children inside a JTree

    hi,
    I did a program where there are informations with a structure of dependence that should be showed inside JTree components.
    I realized this purpose in my program .
    But I am findind very difficult (after having put the information inside the JTre in the start) to show them again inside the JTrees when they are changed.
    I don't know how to remove or change the informations after they are put on the children of the JTree using the methods that I found in the documentation to reach this purpose...
    I need some help ...
    To explain well my problem, and facilitate the helpers, I post some code that show my problem..
    The program show a GUI with some JTrees.
    The informations are contained in two strings, and in the GUI are also two buttons that can load the informations inside the JTree when they are clicked.
    Thank you in advance
    regards
    tonyMrsangelo
    public class JTree_TryToUseIt_ChangingNodes extends javax.swing.JFrame {
        private PanelFulViewConteiner jPanelFulViewConteiner;
        Dimension dimPrefArcPanels = new Dimension(910, 150);
        Dimension dimMinArcPanels = new Dimension(700, 100);
        Dimension dimPrefSemiArcPanels = new Dimension(850, 140);
        Dimension dimMinSemiArcPanels = new Dimension(550, 90);
        Dimension dimPrefBodyXpicPanels = new Dimension(900, 150);
        Dimension dimMinBodyXpicPanels = new Dimension(700, 150);
        Dimension treePrefDim = new Dimension(90, 110); //
        Dimension treeMinDim = new Dimension(60, 110);
        PanelToShowTrees panel_trees;
        public JTree_TryToUseIt_ChangingNodes() {
            getContentPane().setLayout(new GridBagLayout());
            GridBagConstraints gBC = new GridBagConstraints();
            jPanelFulViewConteiner = new PanelFulViewConteiner();
            gBC.gridx = 0;
            gBC.gridy = 0;
            gBC.gridwidth = 10;
            add(jPanelFulViewConteiner, new GridBagConstraints());
            gBC.gridx = 0;
            gBC.gridy = 1;
            gBC.gridwidth = 10;
            pack();
            panel_trees = this.jPanelFulViewConteiner.jPanelFulContainerTop.panelToShowTrees;
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLocation(50, 50);
            setVisible(true);
        private void fillTrees(String[] strings) {
            collapseTrees();
            removeNodes();
            for (int index = 0; index < strings.length; index++) {
                DefaultMutableTreeNode dmt = new DefaultMutableTreeNode(strings[index]);
                String knotStr = strings[index].substring(0, 1);
                int knot = -1;
                try {
                    knot = Integer.parseInt(knotStr);
                } catch (NumberFormatException e) {
                panel_trees.root_Node[knot].add(dmt);
                panel_trees.validate();
                panel_trees.repaint();
            collapseTrees();
        void collapseTrees() {
            for (int i = 0; i < 8; i++) {
                panel_trees.jTree.collapseRow(0);
    panel_trees.jTree[i].expandRow(0);
    panel_trees.validate();
    panel_trees.repaint();
    void removeNodes() {
    for (int i = 0; i < 8; i++) {
    panel_trees.jTree[i].removeAll();
    panel_trees.validate();
    panel_trees.repaint();
    public static void main(String args[]) {
    JTree_TryToUseIt_ChangingNodes xx = new JTree_TryToUseIt_ChangingNodes();
    class PanelFulViewConteiner extends JPanel {
    PanelFulContainerTop jPanelFulContainerTop;
    PanelFulContainerBottom jPanelFulContainerBottom;
    public PanelFulViewConteiner() {
    GridBagLayout gbl = new GridBagLayout();
    this.setLayout(gbl);
    GridBagConstraints gBC = new GridBagConstraints();
    jPanelFulContainerTop = new PanelFulContainerTop();
    gBC.gridx = 0;
    gBC.gridy = 0;
    add(jPanelFulContainerTop, gBC);
    jPanelFulContainerBottom = new PanelFulContainerBottom();
    gBC.gridx = 0;
    gBC.gridy = 2;
    add(jPanelFulContainerBottom, gBC);
    class PanelFulContainerTop extends JPanel {
    PanelToShowTrees panelToShowTrees;
    public PanelFulContainerTop() { // costruttore
    this.setMinimumSize(dimMinArcPanels);
    this.setPreferredSize(dimPrefArcPanels);
    setLayout(new FlowLayout());
    panelToShowTrees = new PanelToShowTrees();
    add(panelToShowTrees);
    }// costruttore
    class PanelFulContainerBottom extends JPanel {
    JButton but1 = new JButton("load string1");
    JButton but2 = new JButton("load string2");
    String[] str1 = {"0-AAA", "0-BBBBBB", "2-CCCCC", "2-DDDDDD", "2-EEEEEEE", "5-FFFFFF", "5-GGGGGG", "5-HHHHHH", "7-IIIIII", "7-KKKKKKK", "7-LLLLLL", "7-MMMMMM"};
    String[] str2 = {"0-aaaaa", "0-bbbbb", "0-cccc", "2-ddddd", "2-eeee", "3-ffffff", "3-gggggg", "3-hhhhh", "4-iiiiii", "4-kkkkk", "7-lllllll", "7-mmmmm", "7-nnnnn"};
    public PanelFulContainerBottom() {// costruttore
    this.setMinimumSize(dimMinArcPanels);
    this.setPreferredSize(dimPrefArcPanels);
    add(but1);
    but1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fillTrees(str1);
    add(but2);
    but2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fillTrees(str2);
    class PanelToShowTrees extends JPanel {
    JScrollPane jScrollPane[];
    JTree jTree[];
    DefaultMutableTreeNode[] root_Node;
    public PanelToShowTrees() {
    this.setMinimumSize(dimMinSemiArcPanels);
    this.setPreferredSize(dimPrefSemiArcPanels);
    setLayout(new FlowLayout());
    jScrollPane = new JScrollPane[8];
    jTree = new JTree[8];
    root_Node = new DefaultMutableTreeNode[8];
    for (int i = 0; i < 8; i++) {
    root_Node[i] = new DefaultMutableTreeNode(" " + (8 - i));
    jTree[i] = new JTree(root_Node[i]);
    jScrollPane[i] = new JScrollPane();
    jScrollPane[i].setViewportView(jTree[i]);
    add(jScrollPane[i]);
    jScrollPane[i].setPreferredSize(treePrefDim);
    jScrollPane[i].setMinimumSize(treeMinDim);
    jTree[i].addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    showContentOfTheTree(e);
    private void showContentOfTheTree(TreeSelectionEvent e) {
    String stringaGotFromEvent = e.getPath().toString();
    JOptionPane.showMessageDialog(rootPane, "found =---> " + stringaGotFromEvent);

    hi Andre,
    thank you for answering me.
    I have not much practice with JTrees so I find some difficulty to use it...
    After I got your advice, I made changed a little the design of my program..
    This it is a program for management of a dentist office, and I would show in 8 JTrees (every jTree root represents the teeth in a dental arch) the treatments that each tooth got.
    How I said, the 8 JTree roots are representing the teeth, and in this architecture the problem is:
    - to add a node to a tree root to indicate a treatment for that tooth;
    - to delete all the children from a jTree root before beginning to add new child, before writing again treatments, when the informations are changed.
    Following your help, I made this two functions to reach this purpose:
    private void assingTreatmentToTooth(int toothNmbr, String strTreatment) {
            DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(strTreatment); // new treatment to add
            DefaultTreeModel model = (DefaultTreeModel) panel_trees.jTreeXdentalRoots[toothNmbr].getModel(); // get model for the root Tree
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) model.getRoot();
            model.insertNodeInto(newChild, parentNode, 0); // always assign 0 as first node
        } // assingTreatmentToTooth()
    private void removeTreatmentFromAtooth(int toothNmbr, int childNmbr) {
            DefaultTreeModel model = (DefaultTreeModel) panel_trees.jTreeXdentalRoots[toothNmbr].getModel();  // get model for the root Tree
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
            model.removeNodeFromParent(child);
        } // removeTreatmentToTooth()when the second function is executed, I get this error:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.tree.DefaultTreeModel cannot be cast to javax.swing.tree.TreeNode
    at the line : DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
    DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
    could you tell me what is wrong ?
    regards
    TonyMrsangelo

  • Crazy!! Tree object Casting... Error

    I've created a Jtree, consisting of objects of type (String x, String y, String z), When i rename a leaf id like the first String "x" in the object to change accordingly and the rest to remain the same...
    I've used a TreeModelListener with the treeNodesChanged methods to listen for a rename and the below code to change it, But i keep getting the following:-
    java.lang.ClassCastException: java.lang.String
    // Code
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    MObject obj = (MObject) node.getUserObject(); //error
    node.setUserObject(new MObject (obj.x, obj.y, obj.z));
    the casting works perfectly in other sections of the code just not here. please help Thx

    pl. giv code for ur MObject and node creation

Maybe you are looking for

  • Mail fonts cut off at the top.

    Suddenly when I'm typing a new mail message, some of the fonts are cut off at the top. Usually capital letters, e.g. "C" you can't see the top of the curve of the letter. Also, when you hit the return, a number of faded dots are in the interval spaci

  • SAP BW SEM-BPS Variables

    Hi All, We are upgrading SAP BW SEM-BPS system from 2.0B to 6.O, in this process i need to collect some information as like below from tables, like BPS Variables----- UPC_VAR , planning sequence----- UPC_PROFILE_BU planning folder(Web)---- BPS_WB pla

  • Price list -- pricing attribute names

    hi, I need to xtract data from the qp_pricing_attributes table, for price break lines and pricing attributes info. The pricing_attribute is stored as 'PRICING_ATTRIBUTE1', 'PRICING_ATTRIBUTE2' etc. I need to know the actual attribute for which the li

  • Help needed to troubleshoot why my MacBook Pro repeatedly drops wifi connection

    We run Mac & PC laptops, iPhone, iPad on occasion, with ATT DSL, 2Wire 2701HG-B Router. First 6 months of enjoying my Mac, no trouble. Then things started to go south. Been dealing with this problem of dropped internet connection for over a year. Got

  • Contents of egathcomp.html

    Good day. I have a T60 and was wondering how to restore the contents of my egathcomp.html/xml files. Right now, my UUID, machine type and serial numbers are either blank or all 0's. Is there a way to restore the information? I already tried doing a c