Question

Can someone please explain this below written code ?

public void setSelectedFolder(final File f){
    if(f != null){
        Runnable r=new Runnable(){
            public void run(){
                target.setText(f.toString());
            }
        };

        try {
            SwingUtilities.invokeLater(r);
        } catch(Exception x) {
        }
    }
}

It is part of Java program which allows user to select a file from a folder and split this file into chunks.

Was it helpful?

Solution

public static void invokeLater(Runnable doRun)
Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI.

The only thing the code does is to put target.setText(f.toString()); in the EDT to be executed there and update your TextFieldsafely. If you don't do that, you could be facing ugly bugs due to Swing not being thread-safe.
Always putting things into EDT isn't good for readability so there's the SwingWorker do that hard work with syncing all your GUI related long running tasks, but in this simple case you wouldn't need to let those SwingWorkers do the work for you, as it is a simple setter without any long waiting times.

That is for the SwingUtilies.invokeLater(), the Runnable in this case is used to have a run() method in which you define the code you wish the EDT has to execute. Normally you use Runnables to create Threads.
But that`s another big chapter, you can find a lot of information about that on the internet.

OTHER TIPS

  • your code has wrong desing,

  • you have got issue with Concurency in Swing

  • FileIO should be wrapped inside try - catch - finally block, not invokeLater

  • if everything ended, then output to AWT/Swing GUI could be wrapped inside invokeLater

  • use SwingWorker (ev. Runnable#Thread) for this idea

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top