The 'null' value most likely appears besides the text you want to see because, by default (at least from what I know), the JTree's tree cell renderer gets the value to be printed/shown from the object's '
toString()
' method.
You could notice this by a simple '
println
' after you get the root of the document:
Node root = IDocument.getDocumentElement();
System.out.println("Root node displayed value: "+root.toString());
And, thus, the null value should appear.
An obvious solution would be to override the object's
toString()
method, but that's not always quite convenient, especially since you are using a class not made by you. ( 'Node' )
So, another option you might go for might be to override the JTree's
TreeCellRenderer
by building a class that implements the interface
TreeCellRenderer
and then attach an instance of it to the JTree object you are using with the
setCellRenderer()
method.
For example:
public class CustomTreeCellRenderer implements TreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Component returnValue = null;
if (value != null && value instanceof Node) {
JLabel thisLabel;
if (((Node) value).getNodeType() != 7 && ((Node) value).getNodeType() != 1)
thisLabel = new JLabel(((Node) value).getNodeValue());
else
thisLabel = new JLabel(((Node) value).getNodeName());
returnValue = thisLabel;
} else {
DefaultTreeCellRenderer thisDefaultRenderer = new DefaultTreeCellRenderer();
returnValue = thisDefaultRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
}
return returnValue;
}
}
Then you can use this class like so:
CustomTreeCellRenderer newRenderer = new CustomTreeCellRenderer();
JTree IJTree = new JTree();
IJTree.setModel(model);
IJTree.setCellRenderer(newRenderer);
Of course, this is just an example. You can tailor the end class to your needs.
I hope this helps.
Cheers!