How to Update the Status Message Using Worker Thread in Eclipse Rcp

Objective:
-To create an eclipse application that will dynamically update the action bar's status message from a worker thread. Updating a part of the screen in another thread is a good practice, since it will not make your screen blink, also the screen will not look like it hanged.

Requirements:
-eclipse-rcp (eclipse.org)

1.) create a new eclipse-rcp project with a view
2.) create a new class which will implement a Runnable interface (worker thread), name it StatusUpdater
public class StatusUpdater implements Runnable {
 private ViewPart1 view;
 
 public StatusUpdater(ViewPart1 view) {
  this.view = view;
 }

 @Override
 public void run() {
  int i = 0;
  while(true) {
   view.updateStatus("Counter: "+i);
   i++;
   try {
    Thread.sleep(1000);
   } catch(InterruptedException e) {
    
   }
  }
 }
}
What you should notice:
-the constructor has a ViewPart1 parameter (which will be the only view that we defined)
-view.updateStatus is a method in the ViewPart1

Going back into the ViewPart1 class
1.) in the createPartControl method, we will instantiate our StatusUpdater class
public void createPartControl(Composite parent) {
 Thread t = new Thread(new StatusUpdater(this));
 t.start();
}

And finally the updateStatus method
 public void updateStatus(final String s) {
  final IActionBars bars = getViewSite().getActionBars();
  //not Display.getCurrent() and new Display(), both will throw exception
  Display.getDefault().asyncExec(new Runnable() {
   @Override
   public void run() {
    bars.getStatusLineManager().setMessage(s);
   }
  });
 }

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post
NERV Open Source

Building production Spring Boot systems?

Explore NERV — open-source Java libraries for audit trails, persistence, exception handling, and reliable event-driven architecture.

Explore NERV on GitHub →