2011-10-25 96 views
1

經過另一個線程的建議,我一直在玩定時器課,沒有太多的快樂。下面有我的代碼:Java定時器的麻煩?

public void buttonImageReveal(ActionEvent e){ 

     Timer gameTimer = new Timer(100, new ActionListener() { 

      public void actionPerformed(ActionEvent e) { 

       repaint(); 
      } 
      }); 

     String temp = e.getActionCommand(); 

     switch(temp){ 
         case "1": 
          System.out.println("case1");        
          ((JButton)e.getSource()).setIcon(one); 
          gameTimer.start(); 
          ((JButton)e.getSource()).setIcon(null); 
          break; 

我要的是在圖像的一個之間有1個第二間隙被示出爲圖標然後該被移除。點擊按鈕時只發生一次。目前,我只是按下一個空白按鈕?

TIA

編輯:

 public void actionPerformed(ActionEvent e) { 
      System.out.println(e); 
      lastImage(); 

     } 

     }); 

public void buttonImageReveal(ActionEvent e){ 

     String temp = e.getActionCommand(); 

     switch(temp){ 
         case "1":      
          ((JButton)e.getSource()).setIcon(one); 
          lastBtn = ((JButton)e.getSource()); 
          gameTimer.start(); 

          break; 

現在做什麼應該,但計時器不斷去和去,你會怎麼做一次你完成,並希望它停止?

回答

4

您設置圖標,啓動計時器,然後立即刪除圖標。來自定時器的start()方法幾乎立即返回並且定時器將異步執行其任務。您需要在actionPerformed方法中刪除圖標。

+1

+1,對於速度更快且具有更好的解釋,不要忘記停止你Timer#stop(),或。 – camickr

+1

如果我這樣做,似乎把它放入一個循環,我不明白爲什麼? –

+0

@EricBanderhide你可以用更新的代碼編輯你的文章嗎?將其粘貼在當前代碼後面以保持原始問題清晰。 –

0

而不是調用repaint()100ms以後(應該是1000ms = 1s,我認爲)稍後更改組件1秒。通過用改變的方法替換repaint()來做到這一點。

1

嘗試將圖標設置爲null時,計時器觸發。我已更新原始線程以及。 因此,代碼應該是:

public void buttonImageReveal(final ActionEvent e){ 

     Timer gameTimer = new Timer(100, new ActionListener() { 

      public void actionPerformed(ActionEvent e) { 

       ((JButton)e.getSource()).setIcon(null); 
      } 
      }); 

     String temp = e.getActionCommand(); 

     switch(temp){ 
         case "1": 
          System.out.println("case1");        
          ((JButton)e.getSource()).setIcon(one); 
          gameTimer.start();         
          break; 
-1

而不是創建一個新的計時器可以使用

Thread.sleep(1000); 

要更換

gameTimer.start(); 
+1

-1在Event Dispatch Thread上調用Thread.sleep()將會阻止GUI重繪自己,因此您仍然不會看到初始圖標。 – camickr

1

你有點compicated簡單的事情,

 timer1 = new Timer(1000, new AbstractAction() { 

     private static final long serialVersionUID = 1L; 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      random = new Random(); 
      SwingUtilities.invokeLater(new Runnable() { 

       @Override 
       public void run() { 
        button1.setSomething(something); 
        button1.validate(); //not required for all methods 
        button1.repaint(); //not required for all methods 
       } 
      }); 
     } 
    }); 
    timer1.setDelay(500); 
    timer1.setRepeats(true); 
    timer1.start(); 

herehere

,如果你想運行此代碼只有一次,然後setRepeats(false)