Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[platform-swt-dev] Using Threads

I'm written a stopwatch class and I need to make use of Threads. However, using the Display.asyncExec() method seems to block the UI.

Is this a bug????

here's a sample code which demostrates what i'm trying to do

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

public class
Async
implements Runnable
{
   int counter = 0;
   Label label;
   boolean isRunning;

   public Async(Label label)
   {
      this.label = label;
   }

   public void
   updateLabel()
   {
      label.setText(String.valueOf(counter));
   }

   public void run()
   {
      try
      {
         while(isRunning)
         {
            Thread.sleep(1000);
            counter++;
            updateLabel();
         }
      }
      catch (InterruptedException e)
      {

      }
   }

   public static void main(String[] args)
   {
      Display display = new Display();
      Shell shell = new Shell(display);
      shell.setLayout(new FillLayout(SWT.VERTICAL));
      Label label = new Label(shell, SWT.NONE);

      Button start_pause = new Button(shell, SWT.CENTER);
      start_pause.setText("Start");
      final Async watch = new Async(label);

      start_pause.addListener(SWT.Selection, new Listener()
      {
         public void
         handleEvent(Event event)
         {
            if (!watch.isRunning)
            {
               watch.isRunning = true;
               Display.getCurrent().asyncExec(watch);
            }
            else
            {
               watch.isRunning = false;
            }
         }
      });

      shell.pack();
      shell.setSize(177, 223);
      shell.open();
      try
      {
         while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) display.sleep ();
         }
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
      display.dispose();
   }
}



Back to the top