tags:

views:

62

answers:

5

Hi I have a little app that at the moment consists of a JPanel with an "Open File" button. Once the user clicks the button a new JFileChooser is created so the user can select a file.

Once the user selected a file, this file will be processed.

What I want to do, is to set the text on the JPanel to "Processing File" While the file is being processed.

I have all the code for this and then after the code, I call the method to actually process the file, but what happens is that it processes the file first and then update the gui components

How do I get around this?

A: 

As you've identified, processing the file means the Swing thread (which invoked this) is waiting for the processing to complete. So you need to invoke this in a separate thread.

The processing should run in parallel with other stuff (including the GUI updates). Once it's complete, it can call back on another component to signal that the GUI can update a status message (See SwingUtilities.invokeLater() and create an appropriate Runnable to do this)

Brian Agnew
A: 

You should process the file in a separate thread. This will allow you to kill two birds with one stone: First, your app will be more responsive. Second, the title change will actually happen.

OTOH, dealing with multithreading is a bit tricky. In particular, you may want to block some operations while the processing thread is running and then you need to rollback upon completion.

Keep in mind that the new thread cannot do GUI operaions directly: The non-GUI thread must use SwingUtilities.invokeLater() to ask the GUI thread to carry out operations on its behalf.

Itay
You could also use Tasks from the Swing Application Framework
DR
Can you clarify your 'rollback' statement ?
Brian Agnew
Rollback: You may want to disable the "open file" menu item while processing takes place. So you do that before you launch your thread. When processing is done, you need to re-enable that menu item. Restoring the original title is also an act of rollback-ing.
Itay
+1  A: 

You should process your task in another thread rather than in Event Dispatch Thread (EDT).

public void actionPerformed(ActionEvent e) { 
  statusLabel.setText("Processing File");

  new Thread(new Runnable() { 
    public void run() { 
      // do something long task
      SwingUtilities.invokeLater(new Runnable() { 
        public void run() { 
          statusLabel.setText("Done!");
        }
      });
    }
  }).start();
}

Using a Swing Worker Thread

xrath
A: 

Read this tutorial

3biga
A: 

Thank you all. Since all of these will work, I am not marking on specific answer as right.

kilhra