[英]Timer in java using Eclipse
我正在嘗試使用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)
關於每秒刷新屏幕的任何想法或示例嗎?
我已按照答案之一中的說明進行操作,但仍然收到相同的錯誤。
為什么不使用SWT Display類內置的計時器功能?
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);
}
});
}
您必須將其拆分為單獨的方法,最好使用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,請以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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.