0

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

4 Answers4

2

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?

Community
  • 1
  • 1
Stefan
  • 444
  • 5
  • 16
  • hi @Stefan Thank you, I was looking for alternative for thread but I think I won't chnage any think on UI at run time without Multi-threading – Rajesh Mhatre Oct 07 '16 at 11:52
2

I believe that it is because your tasks will be executed by default by the Event Dispatch Thread which is responsible for managing all your Swing components as they are not thread-safe. This thread should only execute short tasks otherwise your application will become unresponsive. You should convert your tasks into a sub class of SwingWorker, then you will be able to use a PropertyChangeListener in order to modify the text of your status whenever the progress of your task evolves.

More details about Concurrency in Swing.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
0

you can change the Color using this :

lblStatus.setForeground(Color.red);

and for changing text you can use setText() method , if you have problem with using that send all of the code here

Mohsen_Fatemi
  • 2,183
  • 2
  • 16
  • 25
0

to change color part text use html

lblStatus.setText("<html><b><font color='red'>Phase1 done successfully !!!</font></b>, Phase2 started");
Piotr Rogowski
  • 3,642
  • 19
  • 24