日期:2014-05-20 浏览次数:20790 次
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class TimerDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TimerDemo().new TimerFrame();
}
});
}
class TimerFrame extends JFrame{
private static final long serialVersionUID = 281511492706800685L;
JLabel label = null;
JButton button = null;
List<Timer> list = new ArrayList<Timer>();
public TimerFrame(){
JFrame frame = new JFrame();
frame.setSize(300, 200);
label = new JLabel();
button = new JButton("开始计时");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final Timer timer = new Timer();
for(Timer tim : list){
tim.cancel();
}
list.clear();
if(list.isEmpty()){
list.add(timer);
}
timer.schedule(new TimerTask() {
private int count = 30;
@Override
public void run() {
if(count > 0){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
label.setText( " "+String.valueOf(count--) + " 秒");
}
});
}else{
timer.cancel();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
label.setText("时间到!");
}
});
}
}}, 0, 1000);
}
});
frame.getContentPane().add(label, BorderLayout.NORTH);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
}