首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SWT中的javax.swing.Timer等价物?

SWT中的javax.swing.Timer等价物?
EN

Stack Overflow用户
提问于 2014-03-06 04:48:28
回答 2查看 226关注 0票数 1

我需要一些手段来运行代码在用户界面线程与延迟和中止等待的能力。这可以通过Swing中的javax.swing.Timer来完成。SWT中有类似的功能吗?Display#timerExec没有明显的能力来取消未来的运行。

EN

回答 2

Stack Overflow用户

发布于 2014-03-06 06:03:38

下面是一个使用Display#timerExec(int, Runnable)的示例

代码语言:javascript
复制
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();
}
票数 3
EN

Stack Overflow用户

发布于 2014-03-06 17:33:45

我的目标是使空闲检测器平滑用户界面。当用户对UI的一部分进行更改时,系统将等待1000ms,并更新UI的其他部分。如果在等待期间,例如在800ms内,用户再次进行更改,则系统取消对该时间段的等待,并再次开始等待1000ms。

Swing中,用一次延迟定时器解决了这个问题。Swing的计时器为此做了很好的准备。我想知道,SWT是不是也有同样的东西?

可能没有直接的等价物,所以我用util的定时器做了一个类:

代码语言:javascript
复制
public abstract class DelayedInfrequentAction implements Runnable {

    private int delay;
    private Display display;

    private Timer timer = null;

    public DelayedInfrequentAction(Display display, int delay) {
        this.display = display;
        this.delay = delay;
    }

    public synchronized void kick() {

        if( timer != null ) {
            timer.cancel();
            timer.purge();
            timer = null;
        }

        timer = new Timer(this.getClass().getSimpleName(), true);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                display.syncExec(DelayedInfrequentAction.this);
                synchronized (DelayedInfrequentAction.this) {
                    timer = null;
                }

            }}, delay);

    }

    @Override
    abstract public void run();

}

这不是Swing的计时器等价物,而是利用了utils计时器的取消能力。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22208879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档