Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing multi threads and ui freezes

Can't figure this one out. Using worker or invokeLater, the UI still freeze. After each file is downloaded, I want a JList to be updated. But the JList will only update after the tread returns.

Here is the code:

public class MyUi extends javax.swing.JFrame{
    ...

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

      SwingUtilities.invokeLater(new Runnable() {
         //To get out of the event tread
         public void run() {
            dl(); 
         }
       });
   }

   private void dl(){
      ...
      //ini and run the download class
      Download myDownload = new Download();
      myDownload.doDownload(myDlList);
   }

   public void updateJlist(String myString){

       myModel.addElement(myString);
       jList1.repaint();
   }

}

public class Download{
...

  public void doDownload(String[] fileName){
      for(int i=0; i<fileName.length; i++){
         ...//download action...
         //for my jList1 to be updated after each file.
         MyUi.updateJlist(fileName[i]);
      }
   }

}

Any example would help.

like image 772
marcb Avatar asked Sep 04 '26 00:09

marcb


2 Answers

invokeLater does exactly the opposite of what you expect it to do - it runs operations on the EDT, which explains the behaviour.

like image 134
Hauke Ingmar Schmidt Avatar answered Sep 05 '26 14:09

Hauke Ingmar Schmidt


Download the file on a background thread and wrap just updateJlist() in a Runnable.

SwingWorker would be more reliable.

Addendum: As @mre notes, SwingWorker also makes it easy to report interim results, as shown here.

like image 39
trashgod Avatar answered Sep 05 '26 13:09

trashgod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!