Passing events back to your view in Eclipse

Posted by Mark Drew on code on October 24, 2012

Tagged under java,eclipse

This is going to be a bit of a technical post, and it's to do with views in Eclipse. I tried to find this all over the place but in the end it was bits and pieces from different posts that actually gave me the answer, which is kinda odd.

So, here’s the problem. You are writing a plugin for Eclipse. You have a view, say a TreeViewer in there that is going to be populated with some content. You do the following:

All is great, we have a content provider which basically allows you to find children and parents in your Tree, and the LabelProvider which displays the right image and label for each item.

The content provider is notified when you change anything in the tree, but how about the other way?

So say I have a background process that updates MyDataStore? How do you then tell the tree to refresh?

This is something that has been bugging me for a long while and today I come up with a quick solution, which I hope works.

First off, we want to somehow subscribe to any changes that MyDataStore might recieve. To do that you can make MyDataStore Observable.

Now whenever MyDataStore is changed (for example, when someone calls the updateMeSomehow() method) you should also add the following calls within the method:

Now in your View, you can add a new observer, that will now have the update() methop triggered whenever something changes in myDataStore!

Now that’s not the end of it. If you were to call (as you would presume) myTreeViewer.refresh() you will get a org.eclipse.swt.SWTException: Invalid thread access error. That is because the TreeView is running in a UI thread, and the thread that updated your DataStore is probably in a different thread (usually). So what you need to do is go back to the Display thread and do the update asynchronously.

I know there are few people out there doing this, but hopefully this will help you, since I couldn’t find this answer that easily (in completeness).

References:




comments powered by Disqus