使用Eclipse的java中的计时器

我正在尝试使用Eclipse在Java中执行一个小程序,我有点迷失。

任何人都可以解释我(用“假人的方式”)我需要做什么才能使用计时器重新绘制表格?

我正在尝试做一个像时钟一样简单的事情。 我需要一个计时器来每秒重绘它。

像这样的东西:

private void activateTimer() { ActionListener myAction; myAction = new ActionListener () { public void actionPerformed(ActionEvent e) { whatever.redraw(); } }; myTimer = new Timer(1000, myAction); myTimer.start(); } 

必须执行操作时,我收到错误:

 *Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access* 

这是我收到的完整例外:

 Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access at org.eclipse.swt.SWT.error(SWT.java:4282) at org.eclipse.swt.SWT.error(SWT.java:4197) at org.eclipse.swt.SWT.error(SWT.java:4168) at org.eclipse.swt.widgets.Widget.error(Widget.java:468) at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:359) at org.eclipse.swt.widgets.Control.redraw(Control.java:2327) at default.myTimer$1.actionPerformed(myTimer.java:97) at javax.swing.Timer.fireActionPerformed(Unknown Source) at javax.swing.Timer$DoPostEvent.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$000(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) 

关于每秒刷新一次屏幕的任何想法或任何样本?

我按照其中一个答案中的说明进行操作,但我仍然收到同样的错误。

你必须将它拆分为separete方法,更好的是使用javax.swing.Action而不是ActionListener

 private void activateTimer(){ myTimer = new Timer(1000, myAction); myTimer.start(); } private Action myAction = new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { whatever.redraw(); } }; 

为什么不使用SWT Display类中内置的计时器function?

 private void activateTimer(final Display display) { display.timerExec( 1000, new Runnable() { public void run() { whatever.redraw(); // If you want it to repeat: display.timerExec(1000, this); } }); } 

此页面可能有用。

如果您使用SWT,请以SWT方式执行:)

编辑:

问题是小部件应该由eclipse的线程更新。 试试这个代码。

 Job job = new Job("My Job") { @Override protected IStatus run(IProgressMonitor monitor) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { while(true) { Thread.sleep(1000); whatever.redraw(); } } }); return Status.OK_STATUS; } }; job.schedule();