我想及时添加按钮控件。 这意味着,在shell打开后,它应该开始逐个放置按钮 在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();
}
}
}
});
}
}
答案 0 :(得分:0)
Runnable
的{{1}}在UI线程中运行。因此,您正在进行的timerExec
调用阻止了UI线程 - 永远不会阻止此线程至关重要。 从不在UI线程中调用Thread.sleep
。
您必须使用单独的Thread.sleep
来执行每个步骤,并使用timeExec
调用的延迟参数来指定等待的时间。
所以
timerExec
在500毫秒后运行Runnable,Runnable应该只执行第一步,然后再次调用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);
}
});
以安排下一步。