Search code examples
javaswingtypesjtree

Java DefaultMutableTree incompatible types


Been searching for an answer online but haven't found anything yet. I have created the following method

public void process(DefaultTreeModel tree){
    DefaultMutableTreeNode current = tree.getRoot();
}

However, the compiler is throwing an incompatible type error. The tree is created by creating DefaultMutableTreeNodes from my own class, and then adding them to a DefaultMutableTree (tested and works fine).

Im not sure why the type is incompatible, because when i run the following

public void process(DefaultTreeModel tree){
    Object o = tree.getRoot();
    System.out.println(o.getClass());
}

It outputs:

class javax.swing.tree.DefaultMutableTreeNode

All help much appreciated!


Solution

  • DefaultTreeModel returns an Object when you call getRoot(). The compiler has no information as to what type it will be at runtime, so it assumes it's an Object and cannot cast it to a DefaultMutableTreeNode.

    Even if it's the right class at run time, it cannot know this at compile time. You will have to check it with instanceof

    Object o = tree.getRoot();
    if(o instanceof DefaultMutableTreeNode) {
        DefaultMutableTreeNode root = (DefaultMutableTreeNode)o;
        ...
    }