Question

i'm trying to create a simple program that will upload a few files for me to a windows share. I have all the basic functionality but i have problems with some finishing touches. I have a GUI and i just want to display some information about the upload - a progress bar and a label. Here is the code:

private void btn_UploadActionPerformed(java.awt.event.ActionEvent evt) {

    upl.setFiles(files);

    for(int i = 0; i < files.length; i++){
        progressLabel.setText("Uploading " + files[i].getName());
        upl.uploadFile(i);
        uploadProgress.setValue(uploadProgress.getValue() + 90/files.length);

    }

    uploadProgress.setValue(100);

}

That gets executed when the user presses an Upload button. The problem is, that the setText and setValue don't really work as they should. When i press the upload button the upload starts (and finishes) but the text on the label does not change and neither does the progress bar. They only change when the upload is finished.

The entire source code can be found here: Code

Any suggestions? P.S. In rather new at java :)

Was it helpful?

Solution

I second JB Nizet ,In some cases, using a background thread instead of the event-dispatching thread prevents the user interface from freezing while the task is running.

FYI from the java tutorials,

A Swing programmer deals with the following kinds of threads:

  • Initial threads, the threads that execute initial application code.

  • The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.

  • Worker threads, also known as background threads, where time-consuming background tasks are executed.

OTHER TIPS

You're doing the upload in the event dispatch thread. So the painting code, which is executed in the same thread, can't be executed until the upload is finished. Event handling code should finish as quickly as possible. If you have a long task to execute, it should be executed in a separate, background thread.

Use SwingWorker to do what you want. Its javadoc has an easy to understand example.

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