View Full Version : SelectionChangedEvent.getSource() - ClassCastException with TreeSelectionModel

12 Jan 2012, 6:55 AM
Ok, this appears to be very strange.

I've been playing around with Tree. Mostly working. I have an odd thing happening with the SelectionChangedEvent class and onSelectionChanged method.

My code basically uses the BasicTree from the Demo as a template.

The Tree is a Tree<TreeItem, String> with TreeItem being my own class.

So, my EntryPoint class implements SelectionChangedHandler<TreeItem>, and the onSelectionChanged method signature thus looks as follows:

public void onSelectionChanged(SelectionChangedEvent<TreeItem> event)

Here's where it gets weird.

Inside that method, I can NOT do the following:

if(event.getSource() instanceof TreeSelectionModel<?>)

Eclipse will red-underline it and complain that I have "Incompatible conditional operand types Component and TreeSelectionModel<?>"

If I skip the parameterized <?>, I get basically the same error.

I will also get the same "Incompatible conditional operand..." complaint in the if statement below when I try to do something like this:

TreeSelectionModel selectionModel = myTree.getSelectionModel();
if(event.getSource() == selectionModel) {
// do stuff

So I tried to be circuitous. I instead tried this:

if(event.getSource() instanceof Object) {
Object source = event.getSource();

and figured I would do my instanceof check after the assignment. This will compile, but the line:

if(event.getSource() instanceof Object)
will throw ClassCastException! It complains that TreeSelectionModel cannot be cast to Component

The complaint is actually with line 57 in SelectionChangedEvent.java. That line is trying to downcast an Object (returned by GwtEvent.getSource()) as a Component, and TreeSelectionModel is not in the Component hierarchy.

My workaround is to have a handle to the Tree available, and use the onSelectionChanged method simply to note when the selection has changed. I have to ignore the SelectionChangedEvent instance that's passed in, because I can't do much with it.

However, it looks like SelectionChangedEvent.getSource() should be returning an Object rather than a Component... (unless I'm missing something)