Search code examples
javaswingruntimejlabelevent-dispatch-thread

how to change jlabel text/color at runtime in swing aplicaiton


I am working on project where I am doing three task on a button click which takes aprox. 2-3 mins I am changing jLabel's text using below code

lblStatus.setText( "Phase1 done successfully !!!, Phase2 started " );

but I get only "All phase done successfully !!!" text in jLabel after all run is completed.


Solution

  • If you run your long running task in the EDT, the UI freezes until your task is done. Therefore you should do the long running task in a background thread. Within the background thread you can use SwingUtilties.invokeLater()to update the UI. Example:

    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        lblStatus.setText( "Phase1 done successfully !!!, Phase2 started " );
    }});
    

    For more information see SwingUtilities.invokeLater() why is it needed?