菜鸟学JAVA之Timer

与许多面向对象的编程一样,java也有Timer类,用来计算时间。它在java.swt中。

通过使用Timer可以动态的显示时间

Timer的实现

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Date;

public class mainFrame extends JFrame implements ActionListener {
	private JButton stb,pab,reb;
	private JPanel pan;
	private JTextField text;
	Timer time;
	
	public mainFrame(String s){
		super (s);
		setSize(300,100);
		setLocationRelativeTo(null);
		
		pan=new JPanel();
		this.setContentPane(pan);
		
		stb=new JButton("开始");
		pab=new JButton("停止");
		reb=new JButton("重新开始");
		pan.add(stb);                 //将按钮加入到面板中
		pan.add(pab);
		pan.add(reb);
		stb.addActionListener(this);  //加入相关的监听
		reb.addActionListener(this);
		pab.addActionListener(this);
		text=new JTextField ("时间:**:**:**");
		pan.add(text);
		
		time=new Timer(1000,this);
		
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public void actionPerformed(ActionEvent e){    //重写actionPerformed类来实现事件处理
		if (e.getSource()==time){
			Date d=new Date();
			String s=d.toString().substring(11,19);
			text.setText("时间:"+s);
		}
		else if (e.getSource()==stb){
			time.start();
		}
		else if (e.getSource()==pab){
			time.stop();
		}
		else if (e.getSource()==reb){
			time.restart();
		}
	}

}

通过mainFrame类来新建一个窗体,并对按钮事件进行处理。通过time=new Timer(1000,this)来实例化Timer,并且让它每隔1000ms触发一次actionPerformed事件,从而动态的显示时间。

public class text {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		mainFrame mf =new mainFrame("我能算时间");   //实例mainFrame来查看效果
		
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章