Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

Updating the status message dynamically of an eclipse rcp application by using a worker thread

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);
   }
  });
 }
Updating the status message dynamically of an eclipse rcp application by using a worker thread Updating the status message dynamically of an eclipse rcp application by using a worker thread Reviewed by czetsuya on Monday, November 23, 2009 Rating: 5

No comments:

Powered by Blogger.