在swt中使用java.util.Timer

时间:2014-02-14 08:18:55

标签: java swt

这是我的代码:

new Button(shell,SWT.PUSH).addListener(SWT.Selection,new Listener() {
        @Override
        public void handleEvent(Event event) {
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    label.setText(String.valueOf(System.currentTimeMillis()-start[0]));
                    start[0] = System.currentTimeMillis();
                }
            },100);
        }
    });

比我收到错误:

Exception in thread "Timer-0" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(SWT.java:4397)
at org.eclipse.swt.SWT.error(SWT.java:4312)
at org.eclipse.swt.SWT.error(SWT.java:4283)
at org.eclipse.swt.widgets.Widget.error(Widget.java:472)
at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:363)
at org.eclipse.swt.widgets.Label.setText(Label.java:386)
at Main$2$1.run(Main.java:51)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)

如何改进代码? (display.timerExec()除外)

1 个答案:

答案 0 :(得分:3)

尝试使用asyncExec(未测试)

    new Button(shell,SWT.PUSH).addListener(SWT.Selection,new Listener() {
        @Override
            public void handleEvent(Event event) {
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        Display.getDefault().asyncExec(new Runnable() {
                            public void run() {
                                label.setText(String.valueOf(System.currentTimeMillis()-start[0]));
                                start[0] = System.currentTimeMillis();
                            }
                        }
                    }
                },100);
            }
        });

希望有所帮助

PS:看一下this本书。