简体   繁体   中英

Use java.util.Timer in swt

This is my code:

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);
        }
    });

than I got an error:

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)

How to improve the code? ( except display.timerExec() )

Try using asyncExec (not tested)

    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);
            }
        });

Hope it helps

PS: Take a look at this book.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM