我想及时添加按钮控件。这意味着,在外壳打开后,它应该在1秒的延迟内开始逐个放置按钮。我写的程序,但是它不能工作。只有在放置了所有控件后,所有按钮才可见。我猜是某种更新问题。以下是我的代码。
public class DelayAddingComponentsExample {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setSize(200, 200);
shell.setLayout(new FillLayout(SWT.VERTICAL));
addAutomatically(shell);
// removeAutomatically(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
public static void addAutomatically(final Shell shell) {
for (int i = 0; i < 5; i++) {
final Button button = new Button(shell, SWT.NONE);
button.setText("Button" + i);
button.setVisible(false);
}
shell.getDisplay().timerExec(0, new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(500);
final Button button = new Button(shell, SWT.NONE);
button.setText("Button" + i);
button.setVisible(true);
shell.pack();
shell.layout(true);
shell.redraw();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
public static void removeAutomatically(final Shell shell) {
for (int i = 0; i < 5; i++) {
final Button button = new Button(shell, SWT.NONE);
button.setText("Button" + i);
shell.layout(true);
}
shell.getDisplay().timerExec(0, new Runnable() {
@Override
public void run() {
Control[] controls = shell.getChildren();
for (Control control : controls) {
try {
Thread.sleep(500);
control.dispose();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}发布于 2016-05-04 21:16:49
提供给timerExec的Runnable在UI线程中运行。所以你正在进行的Thread.sleep调用阻塞了UI线程--你永远不要阻塞这个线程,这一点至关重要。从不在UI线程中调用Thread.sleep。
您必须使用单独的timeExec调用完成每个步骤,并使用timerExec调用的delay参数指定等待多长时间。
所以
shell.getDisplay().timerExec(500, new Runnable() {
@Override
public void run()
{
// TODO code for the first button only
// Schedule next update
shell.getDisplay().timerExec(500, .... code for second button);
}
});在500毫秒后运行Runnable,Runnable应该只执行第一步,然后再次调用timerExec来调度下一步。
https://stackoverflow.com/questions/37027071
复制相似问题