我需要一些方法来延迟地在用户界面线程上运行代码并能够中止等待。这可以通过 Swing
中的 javax.swing.Timer
来完成。 SWT
中是否有类似的功能? Display#timerExec
没有取消 future 运行的明显能力。
最佳答案
这是一个使用 Display#timerExec(int, Runnable)
的例子:
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout(SWT.VERTICAL));
final Text text = new Text(shell, SWT.BORDER);
final Button runButton = new Button(shell, SWT.CHECK);
runButton.setText("Stop");
final Runnable run = new Runnable()
{
private int counter = 0;
@Override
public void run()
{
if(runButton.getSelection())
return;
text.setText(Integer.toString(counter++));
display.timerExec(1000, this);
}
};
display.timerExec(1000, run);
runButton.addListener(SWT.Selection, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
if(!runButton.getSelection())
display.timerExec(1000, run);
}
});
shell.pack();
shell.setSize(200, shell.getSize().y);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
关于SWT 中的 javax.swing.Timer 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22208879/