Friday, August 01, 2008

JApplet and the Swing EDT

So, everyone knows by now that doing anything relating to Swing controls when you're not running in the Swing Event Dispatch Thread (EDT) is a big no-no. Unfortunately this is very easy to do, as Swing doesn't enforce this rule and 90% of the time your code will run with no visible problems if you don't do it (right up until you release it to a customer, at which point bugs will become immediately visible).

A lot of the time it's reasonable that Swing doesn't force execution onto the EDT, certainly in high-level application classes, although the closer you get to the Swing classes the more sense it makes to actually enforce the rule in some way.

For instance when writing an application it's up to the developer to get on the Swing EDT before you create and display your Swing controls. However there are other situations in which it's obvious that Swing controls are going to be used and so Swing should put you on the EDT by default: when you're using JApplet for example.

I hadn't noticed before now but I was surprised to notice that JApplet.init() is not invoked on the EDT. Try it:

public class TestApplet extends JApplet {
public void init() {
System.out.println("JApplet.init - EDT = " +
Now if you're using a JApplet you obviously want to do Swing stuff in your applet, so why not help people out and start them off on the Swing EDT?

I guess the issue with doing it by default is that people who don't know about the EDT rule wouldn't be aware that it is being done for them, so you're just avoiding potential bugs without people learning what is involved in avoiding the bugs, so they may just get into another EDT problem further down the line. That may be true, and Swing is definitely an API not a 'framework', allowing you to write code without any help or guidance on how things should be done correctly along the way, but I still think that you should at least start people off on the right track whenever you can - what they do after that is up to them.

No comments: