[Biojava-l] Cast to Sequence
Tom Oinn
tmo at ebi.ac.uk
Sun Jul 31 09:22:15 EDT 2005
Jacob Rohde wrote:
> Hi,
>
> I'm having a problem with a JTree and rendering of Sequences.
>
> Since the JTree calls toString() on objects when displaying them, I
> had to make my own TreeCellRenderer because the Sequence toString
> method prints out debug info.
>
> My code looks like this:
>
> public class FeatureTreeCellRenderer extends DefaultTreeCellRenderer
> {
> public Component getTreeCellRendererComponent(JTree tree, Object value,
> boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
> {
> JLabel l = (JLabel) super.getTreeCellRendererComponent(tree,
> value, sel, expanded, leaf, row, hasFocus);
>
> if(leaf)
> {
> System.out.println(value);
> Sequence s = (Sequence) value;
> l.setText(s.getName());
> }
> return l;
> }
> }
>
> My problem is that I always get a ClassCastException. The weird thing
> is that the println method call above the cast clearly shows that the
> cast should be possible.
In no way whatsoever does it show that :)
The 'value' supplied to the renderer is the implementation of the
TreeNode interface used in the TreeModel you're rendering over. In this
case, as you are presumably subclassing DefaultTreeModel and
DefaultMutableTreeNode you're getting value set to an instance of
DefaultMutableTreeNode which of course can't be cast to a Sequence.
The confusion comes because the toString method of
DefaultMutableTreeNode is something like 'return userObject.toString()'
and so produces exactly the same result in your print statement as you'd
get if it were the user object (in this case your Sequence).
You should use : Sequence s =
(Sequence)((DefaultMutableTreeNode)getUserObject()); instead, and next
time read the javadoc for TreeCellRenderer and the like more carefully :)
Tom
More information about the Biojava-l
mailing list