当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
Java计时器Timer和TimerTask用法总结
发布时间:2010/6/25 11:34:25 来源:城市学习网 编辑:ziteng
  下面给两份源码,一份是基本的,一份是整合JFrame的,不过这个整合和俺的需求不符,所以没用上。
  下面是基本类的使用源码:
  package com.sy.game.test;
  import java.util.Timer;
  import java.util.TimerTask;
  public class TimeTask {
  public static void main(String[] args) {
  TimeTask tTask=new TimeTask();
  tTask.timeVoid();
  }
  public void timeVoid(){
  final Timer timer = new Timer();
  TimerTask tt=new TimerTask() {
  @Override
  public void run() {
  System.out.println("到点啦!");
  timer.cancel();
  }
  };
  timer.schedule(tt, 3000);
  }
  }
  整合的:
  /*
  * java倒计时器
  * shiyang
  * */
  package com.sy.game.test;
  import java.awt.Container;
  import java.awt.FlowLayout;
  import java.awt.Toolkit;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import javax.swing.JButton;
  import javax.swing.JFrame;
  import javax.swing.JPanel;
  import javax.swing.JTextField;
  import javax.swing.Timer;
  @SuppressWarnings("unused")
  public class TimeController extends JFrame implements ActionListener {
  private static final long serialVersionUID = 4603262282860990473L;
  private static final int DEFAULT_WIDTH = 200;
  private static final int DEFAULT_HEIGHT = 100;
  private static final int width = Toolkit.getDefaultToolkit()
  .getScreenSize().width;
  private static final int height = Toolkit.getDefaultToolkit()
  .getScreenSize().height;
  private Container container;
  private JButton btn;
  private JTextField jtfTime;
  private Timer tmr;
  public TimeController() {
  initComponents();
  Timer tmr = new Timer(1000, this);
  this.tmr = tmr;
  setVisible(true);
  }[NextPage]   private void initComponents() {
  this.setTitle("SY秒表");
  this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  this.setResizable(false);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setLocation((width - DEFAULT_WIDTH) / 2,
  (height - DEFAULT_HEIGHT) / 2);
  jtfTime = new JTextField("10");
  btn = new JButton("开始倒计时");
  container = getContentPane();
  JPanel panel = new JPanel();
  panel.add(btn);
  panel.add(jtfTime);
  this.add(panel);
  btn.addActionListener(this);
  }
  public void actionPerformed(ActionEvent ae) {
  if (ae.getSource() == btn) {
  jtfTime.setText("10");
  tmr.start();
  } else {
  int t;
  t = Integer.parseInt(jtfTime.getText());
  t--;
  jtfTime.setText("" + t);
  if (t <= 0) {
  tmr.stop();
  }
  }
  }
  public static void main(String[] args) {
  TimeController timeController = new TimeController();
  }
  }
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved