Monday, June 15, 2009

Swing Event Notification Ordering

A problem that I run into from time to time is listeners getting callbacks in a different order than I want. For example, I might have a model that I want updated before I display something that uses it, but both the model update and the display get triggered by a mouse event. If they get handled in the wrong order, then the display will be incorrect.

There is an open bug regarding this issue and some discussion about it here and here. However, I don't believe Sun has addressed it yet.

One solution would be to rely on the fact that listeners get notified in the reverse order that they were added. But officially the order is undefined, which could cause your code to break if the Java SDK changes.

If you want to be called after other listeners have been notified, a better solution is to use SwingUtilities.invokeLater(), which adds your Runnable to the end of the EDT (event dispatcher thread). This works for the example above.

I'm not sure what would be a good way to get called before other listeners though.

No comments: