我有以下类。
- 为什么总是使能
btnDecorate
?我想在循环正在处理时禁用该按钮。 - 为什么
text.redraw()
只在循环结束时起作用?我想在每个角色上依次看到这个方框。
,
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class SampleRefreshStyledText {
public static void main(String[] args) {
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout(SWT.VERTICAL));
final Button btnDecorate = new Button(shell, SWT.NONE);
btnDecorate.setText("Decorate");
final StyledText text = new StyledText(shell, SWT.NONE);
text.setText("ABCDEFGHIJKLMNOPRQn1234567890");
btnDecorate.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent event) {
btnDecorate.setEnabled(false);
for (int i = 0; i < text.getText().length(); i++) {
StyleRange styleRange = new StyleRange();
styleRange.start = i;
styleRange.length = 1;
styleRange.borderColor = display.getSystemColor(SWT.COLOR_RED);
styleRange.borderStyle = SWT.BORDER_SOLID;
styleRange.background = display.getSystemColor(SWT.COLOR_GRAY);
text.setStyleRange(null);
text.setStyleRange(styleRange);
text.redraw();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
btnDecorate.setEnabled(true);
}
@Override
public void widgetDefaultSelected(SelectionEvent arg0) {}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}
不能用SWT编写这样的循环。
所有UI操作都发生在单个UI线程上。调用Thread.sleep
会使UI线程进入睡眠状态,不会发生任何事情。
redraw
调用只请求重新绘制文本,直到下次display.readAndDispatch()
运行时才实际发生,因此在循环中重复执行此操作是行不通的。
你要做的就是运行循环的第一步一次。然后,您必须安排在500毫秒后运行下一步,而不阻塞线程。您可以使用Display.timerExec
方法来请求稍后运行代码:
display.timerExec(500, runnable);
其中runnable
是实现Runnable
的类,执行下一步。在这段代码的末尾,您可以再次调用timerExec
,直到您完成了所有步骤。