2011-09-22 49 views
1

我正在製作一個簡單的目標射擊遊戲。我在標籤內有一個倒計時定時器和一個閃爍在面板內隨機位置的對象。每次我點擊對象時,該對象的計時器停止,使對象停止,但倒數計時器不會,這是我的問題。我想倒數計時器也應該停止。如何在拍攝對象後停止定時器功能?

有人可以幫我解決這個問題嗎?

下面的代碼:

private void starting() 
{ 
    new Timer(TIMER_PERIOD, new ActionListener() 
    { 
     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      if (count++ < MAX_COUNT) 
      { 
       String text = "Time remaining: (" + (MAX_COUNT - count) + ") seconds left"; 
       setCountDownLabelText(text); 
       Date date = new Date(); 
       setCountDownPanelText(date); 

      } 
      else 
      { 
       ((Timer) e.getSource()).stop(); 
       randomTimer.stop(); 
       JOptionPane.showMessageDialog(null, "Game Over"); 
       System.exit(0); 
      } 
     } 
    }).start(); 
} 
+2

請提供[sscce](http://sscce.org/),展示您描述的問題。 – trashgod

回答

5

我感到那你不明白的代碼在所有的,你是不知道是延長Timer創建匿名類,它(如果你願意看到的該文檔)有一個功能stop()這就是你所要求的。

您需要存儲對定時器的引用。

private javax.swing.Timer timer; 

private void starting() { 
    timer = new Timer(TIMER_PERIOD, new ActionListener() 
    { 
     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      // do stuff 

      // stop the timer 
      timer.stop(); 

      // do other stuff 
     } 
    } 
} 
+1

-1用於混合單獨的類a)在Swing中使用的Timer是swing包中的一個(不是在util中的一個)b)util.Timer具有方法cancel,但沒有構造方法接受ActionListener c) swing.Timer沒有方法取消,但方法停止。 – kleopatra

+1

@Charles Goodwin請將1)java.util.Timer更改爲javax.swing.Timer,2)timer.stop(),3)鏈接到今天的Java6或7 API – mKorbel

+0

@mKorbel完成它 –