不少人遇到过SWT中画面阻塞的问题,下面是一个解决方法,可供参照:
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ThreadTest {
private Display display = null;
private Shell shell = null;
private int width = 600;
private int height = 450;
private Control movable = null;
private Button action = null;
private Thread thread = null;
private boolean threadState = true;
private static final Object LOCK = new Object();
public ThreadTest() {
display = Display.getDefault();
shell = new Shell(display, SWT.SHELL_TRIM);
shell.setSize(width, height);
shell.setText("Thread Test");
shell.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent arg0) {
thread.interrupt();
System.exit(0);
}
});
Rectangle monitorBounds = display.getPrimaryMonitor().getBounds();
shell.setLocation((monitorBounds.width - width) / 2, (monitorBounds.height - height) / 2);
initMovableComposite();
initThread();
initActionButton();
shell.layout();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
private void initThread() {
thread = new Thread() {
Runnable runnable = new Runnable() {
int deltX, deltY;
Rectangle rect;
public void run() {
rect = movable.getBounds();
if (rect.x + rect.width >= shell.getBounds().width) {
deltX = -1;
} else if (rect.x <= 0) {
deltX = 1;
}
if (rect.y + rect.width >= shell.getBounds().height) {
deltY = -1;
} else if (rect.y <= 0) {
deltY = 1;
}
movable.setLocation(rect.x + deltX, rect.y + deltY);
}
};
public void run() {
while (true) {
synchronized (LOCK) {
if (threadState) {
display.syncExec(runnable);
try {
sleep(8);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
};
}
private void initMovableComposite() {
movable = new Button(shell, SWT.TRANSPARENCY_ALPHA);
((Button)movable).setText("O");
movable.setBounds(0, 0, 80, 24);
}
private void initActionButton() {
action = new Button(shell, SWT.ARROW | SWT.DOWN);
action.setText("Act");
int w = 80;
int h = 25;
action.setBounds((width - w) / 2, h % 10, w, h);
action.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
if (!thread.isAlive()) {
thread.start();
} else {
threadState = !threadState;
}
}
public void widgetDefaultSelected(SelectionEvent event) {}
});
}
public static void main(String[] args) {
new ThreadTest();
}
}
SWT中的线程同步_Display.syncExec(Runnable)
最新推荐文章于 2021-02-21 18:43:27 发布