2013-04-29 64 views
1

我该如何调整这Timer代码,以便它执行四次然后停止?让摆动计时器执行N次?

timer = new Timer(1250, new java.awt.event.ActionListener() { 
    @Override 
    public void actionPerformed(java.awt.event.ActionEvent e) { 
     System.out.println("Say hello"); 
    } 
}); 
timer.start(); 
+0

你可以对你正在尝试做一些更具体的?详细说明定时器的时间。 – 2013-04-29 13:57:22

+0

你的意思是你希望你的'ActionListener'执行4次然后停止? – 2013-04-29 13:58:22

+0

Guillaume Polet:是的, – JaLe29 2013-04-29 14:07:06

回答

3

你可以这样做:

Timer timercasovac = new Timer(1250, new ActionListener() { 
    private int counter; 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     System.out.println("Say hello"); 
     counter++; 
     if (counter == 4) { 
      ((Timer)e.getSource()).stop(); 
     } 
    } 
}); 
timercasovac.start(); 
+0

Thx,为什么1000延迟? – JaLe29 2013-04-29 13:57:26

+0

我想让计时器只有4次.. – JaLe29 2013-04-29 14:01:44

2

你需要自己算,然后Timer手动停止:

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 
import javax.swing.Timer; 

public class TestTimer { 

    private int count = 0; 
    private Timer timer; 
    private JLabel label; 

    private void initUI() { 
     JFrame frame = new JFrame("test"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     label = new JLabel(String.valueOf(count)); 
     frame.add(label); 
     frame.pack(); 
     frame.setVisible(true); 
     timer = new Timer(1250, new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (count < 4) { 
        count++; 
        label.setText(String.valueOf(count)); 
       } else { 
        timer.stop(); 
       } 
      } 
     }); 
     timer.start(); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new TestTimer().initUI(); 
      } 
     }); 
    } 

}