gpt4 book ai didi

java - 使用 Eclipse 在 Java 中使用定时器

转载 作者:行者123 更新时间:2023-11-30 06:33:55 24 4
gpt4 key购买 nike

我正在尝试使用 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)

关于每秒刷新屏幕的任何想法或示例?

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

最佳答案

您必须将其拆分为单独的方法,最好使用 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();
}
};

关于java - 使用 Eclipse 在 Java 中使用定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7552596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com