javaswingrunnableswingutilitiesinvokelater

Why should I use a separate thread to show a GUI in JAVA


This simple issue confuses me. You can display a JAVA GUI application by setting the frames' setVisible property true. But in almost all the examples I found on internet they use a separate thread to do the same thing.

They do something like this,

SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
        new Frame().setvisible(true);  //just take the idea of this line
    }
});

I found no difference between the two methods. But there must be some special reason, that's why everyone is doing this.

Can someone explain it..thanks!


Solution

  • The main reason for launching your application in this way is that Swing components are not thread-safe so you need to guarantee which thread your GUI will start from: the one called the Event Dispatching Thread (EDT). Without doing this, you can't be sure what thread it will start in, but as noted by several kind commentators, the main thread is guaranteed not to be the EDT.

    You should only create, access, or modify UI components from within the EDT. Doing otherwise will result in unexpected behavior (if you're lucky) and/or dirty repaints.

    Some resources I suggest you become familiar with:

    You could also have a read of Why does my boilerplate Java desktop app JFrame use EventQueue.invokeLater in the main method?

    UPDATE

    This is the blog I've been trying to find :P

    This basically explains why it's important to sync your main with the EDT before getting started, it also describes some of the details about why.

    It also describes why many developers make this fundamental mistake when starting their applications (basically, we were told we could, but we never were really allowed to...bad us)