How to update java GUI from Thread?

java, swing

Solution

I think you will have to put the whole while loop into a thread. Otherwise the loop will block your ActionEvent and thus freezes the UI.

Something like:

new Thread(){
    public void run(){
        while(!p.finish){
           SwingUtilities.invokeLater(new Runnable(){
             public void run(){
               ProgressPrecent.setValue(Producer.ProgressPercent);
             }
           }); 
           try{
              Thread.sleep(100);
           }catch(...){}
        }
    }
}.start();

Problem

``` private void StartActionPerformed(java.awt.event.ActionEvent evt) { Queue queue=new Queue(); int target=Integer.parseInt(Target.getText()); String path=Path.getText(); final Producer p=new Producer(queue, target); Consumer c=new Consumer(queue); p.start(); c.start(); while(p.finish !=true) { Runnable r = new Runnable() { public void run() { ProgressPrecent.setValue(Producer.ProgressPercent); } }; if(EventQueue.isDispatchThread()) { r.run(); } else { EventQueue.invokeLater(r); } } } ``` I have two classes that have a shared Queue. one of them is Producer that produces till a target other one consume those elements. all of two extends Thread. I want to display the progress percent to the user, but it freeze my GUI so what should I do?

Original source

Related problems