2016-03-01 80 views
0

我想在每次點擊一個按鈕時在一個小程序中執行一個動畫。我第一次點擊按鈕一切正常。但第二次,動畫的速度在增加。第三次動畫的速度增加了一點點,第四次,第五次......每當我點擊一個按鈕,計時器就會增加速度

我不知道計時器發生了什麼。我該如何解決它?

在小程序我使用此代碼:

JButton btnIniciar = new JButton("Iniciar"); 
    btnIniciar.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) {  
      Timer timer = new Timer(50, new ActionListener(){ 
       public void actionPerformed(ActionEvent e) { 
        //I have a list of packages to animate 
        for (Package p: listaPaquetes){ 
         p.animate(); 
         panel.repaint(); 
        }        
       } 
      }); 

      timer.start(); 
     } 

這是重繪的面板代碼:

protected void paintComponent(Graphics g) { 
    super.paintComponent(g);  
    //I use the same list of the applet 
    for (Package p: listaPaquetes){ 
     //Paint the package 
     p.paintPackage(g); 
    } 

} 

This is how it works, the animation sends packages from left to right

回答

2

當你按你所創建的按鈕新的javax.swing.Timer並調用timer.start(),在這種情況下,按鈕按下後50ms運行,每50ms重複一次。

當您再次按下按鈕時,您將創建並啓動另一個定時器(一個新的定時器),該定時器每隔50ms以50ms的初始延遲再次工作。現在您基本上將重新調用次數加倍。

隨着第三次按下,你重新調用重新調用的次數,因爲你有3個定時器在運行。

如果按鈕的按下時間正確,它看起來好像速度增加了三倍(3按鈕按下)。

如果不希望這種行爲可以防止timer運行,如果它已經在運行這樣的:

private Timer timer = null; 

// ... 

JButton btnIniciar = new JButton("Iniciar"); 
btnIniciar.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent arg0) { 
     // prevent the timer from running again if it is already running 
     if (timer != null && timer.isRunning()) return; 

     timer = new Timer(50, new ActionListener(){ 
      public void actionPerformed(ActionEvent e) { 
       //I have a list of packages to animate 
       for (Package p: listaPaquetes){ 
        p.animate(); 
        panel.repaint(); 
       }        
      } 
     }); 

     timer.start(); 
    } 

請注意,你需要做timer到一個實例變量。與

if (timer != null) return; 

我只是想告訴你,TimerisRunning()方法

if (timer != null && timer.isRunning()) return; 

:您也可以更換線。

您也可以通過調用timer.stop()方法來停止timer

+0

已解決。我不知道把計時器停在哪裏,所以每次按下按鈕時,我也停止計時器,除了第一次。 – carlbron

相關問題