[
Date Prev][
Date Next][
Thread Prev][
Thread Next][
Date Index][
Thread Index]
[
List Home]
[platform-swt-dev] about swt thread.
|
Hi,
I have a problem about swt thread. please see below code.
Press button two to create a thread, and let it refresh button one's text.
But I press button two again, and want to stop the refresh action.
It seems that I have lost the widget's control.
According to eclipse platform api, the caller of asyncExec() method and
the new thread are parallel. So when the new thread is running, I can do
some operation. How to resolve?
Thanks.
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle
;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Test {
Display display = new Display();
Shell shell = new Shell(display);
Button buttonOne = new Button(shell, SWT.PUSH
);
Button buttonTwo = new Button(shell, SWT.PUSH);
static volatile boolean isRunning = false;
public Test() {
shell.setText("Test");
shell.setSize(200, 100);
Rectangle clientArea = shell.getClientArea
();
buttonOne.setText("Test Only");
buttonOne.setBounds(clientArea.x, clientArea.y,
clientArea.width, clientArea.height / 2);
buttonTwo.setText("Start");
buttonTwo.setBounds(clientArea.x, clientArea.y + clientArea.height / 2,
clientArea.width, clientArea.height / 2);
buttonTwo.addSelectionListener
(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (isRunning)
buttonTwo.setText("Sart");
else
buttonTwo.setText("Stop");
isRunning = !isRunning;
getTask(buttonOne).start();
}
});
shell.open
();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
public static void main(String[] args) {
System.out.println("start is running : " + isRunning);
new Test();
}
public Thread getTask(Button button) {
final Button theButton = button;
return new Thread() {
public void run() {
display.asyncExec(new Runnable() {
public void run() {
int i;
while (isRunning)
{
i = (int) (Math.random() * 10000);
theButton.setText("Get num : " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
};
}
}