菜鸟学JAVA之Timer

编程知识 行业动态 更新时间:2024-06-13 00:22:04

与许多面向对象的编程一样,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来查看效果
		
	}

}

更多推荐

菜鸟学JAVA之Timer

本文发布于:2023-04-01 16:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/b95fed75dc346abd5a6d645b43577d7a.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:菜鸟   JAVA   Timer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!