2013-07-31 24 views
1

我有一個在Netbeans中的應用程序,我不知道如何在Java中使用Timer。在Winform中有一個Timer的控制箱,它只能拖拽和使用。現在我想在about.setIcon(about4);(這是GIF)執行後使用一個定時器1秒鐘。如何使用定時器

import javax.swing.ImageIcon;  
int a2 = 0, a3 = 1, a4 = 2; 

ImageIcon about2 = new ImageIcon(getClass().getResource("/2What-is-the-Game.gif")); 
    about2.getImage().flush(); 
    ImageIcon about3 = new ImageIcon(getClass().getResource("/3How-to-play.gif")); 
    about3.getImage().flush(); 
    ImageIcon about4 = new ImageIcon(getClass().getResource("/4About-end.gif")); 
    about4.getImage().flush(); 
    if(a2 == 0) 
    { 
     a2=1; 
     a3=1; 
    about.setIcon(about2); 
    } 
    else if (a3 == 1) 
    { 
     a3=0; 
     a4=1; 

     about.setIcon(about3); 
    } 
    else if (a4 == 1) 
    { 
     a4=0; 
     a2=0; 
     about.setIcon(about4); 

    } 
} 

我該如何做到這一點?

+0

如果你與Swing組件一起使用這個,你最好使用的Java Swing計時器。 – mre

回答

1

在Java中,我們有定時器實現的幾種方式或者更確切地說,它的用途,其中的一些是─

  • 要直到執行任務而設立延遲的具體金額。
  • 查找兩個特定事件之間的時間差。

Timer class爲線程提供工具,用於在後臺線程中安排將來執行的任務。可以安排一次性執行任務,或定期重複執行任務。

public class JavaReminder { 
    Timer timer; 

    public JavaReminder(int seconds) { 
     timer = new Timer(); //At this line a new Thread will be created 
     timer.schedule(new RemindTask(), seconds*1000); //delay in milliseconds 
    } 

    class RemindTask extends TimerTask { 

     @Override 
     public void run() { 
      System.out.println("ReminderTask is completed by Java timer"); 
      timer.cancel(); //Not necessary because we call System.exit 
      //System.exit(0); //Stops the AWT thread (and everything else) 
     } 
    } 

    public static void main(String args[]) { 
     System.out.println("Java timer is about to start"); 
     JavaReminder reminderBeep = new JavaReminder(5); 
     System.out.println("Remindertask is scheduled with Java timer."); 
    } 
} 

瞭解更多從這裏:

+0

哇這是非常有用的信息謝謝! :) – Miki

0

在代碼中聲明一個java.util.Timer的實例(在構造函數中?),並使用docs中的方法來配置/控制它。

import java.util.Timer; 
import java.util.TimerTask; 
... 
private Timer t; 
public class MyClass() 
{ 
    t=new Timer(new TimerTask(){ 
     @Override 
     public void run() 
     { 
      //Code to run when timer ticks. 
     } 
    },1000);//Run in 1000ms 
} 
+0

你可以把它的語法?對不起結果 – Miki

+0

這樣的事情應該工作,文檔顯示所有可能的參數配置,如果你想它在設定的日期等運行等 – Robadob

+0

是代碼說。它會執行我放在run()上的任何代碼。 1秒後還是1秒前? – Miki