Swing programs must ensure that all GUI work is done on the Event Dispatch Thread. Failure to do this leads to unpredictable results. You can use SwingUtilitiies.invokeLater() and SwingWorker, but it’s easy to get the correct use of these wrong, or forget. (Come on guys, it’s 2005, we should have a Thread-safe GUI library by now…)

So, thinking I could be clever, and use a dynamic proxy to intercept all method calls on Swing objects and check that they are being invoked on the EDT, dumping a stack trace if not, off I set.

Wrong – the standard Java dynamic proxy only works when you have classes implementing interfaces, and I just wanted to attach an interceptor on all Swing component classes.

Enter CGLIB, and its Enhancer class. Much better, and I could write a custom ClassLoader that attaches the MethodInterceptor to each class – solution!

Er, no.

This’ll work fine, if I use the target class as the Enhancer’s subclass, then create an instance of the class, and use the – now proxied – class in my app.

The problem comes when I realise I have many zillions of JButton b = new JButton("Some Text"); lines in my software. I really don’t want to have to change all of this to use a Factory that instantiates a proxied component.

I feel there really must be a way of doing this, but it eludes my sight at the moment, and I really have more pressing concerns ATM.

However, a random search on good old Google turned up:
ClientJava – Easily find Swing Threading Mistakes – which achieves the end result in a different way.

Result! Oh frabjous joy…..

Advertisements