极简版秒表(java GUI)

package javaPractice;

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

public class Stopwatch {
	public static void main(String[] args) {
		new Timer();
	}
}

class Timer extends JFrame{
	JLabel jl;
	JTextField jt1,jt2;
	JButton jb;
	SimpleDateFormat df;
	private static TimeNow thread;
	
	Timer(){
		this.setSize(400,300);//初始化窗口
		this.setTitle("Stopwatch");
		this.setLayout(null);
		
		df = new SimpleDateFormat("hh:mm:ss");//设置时间格式
		
		jt1 = new JTextField();//实例化组件
		jt2 = new JTextField();
		jb = new JButton("Current time");
		
		jt1.setText(df.format(new Date()));
		jt1.setBounds(105,50,120,35);//定义各组件的显示位置和大小
		jb.setBounds(90,110,150,30);
		jt2.setBounds(105,170,120,35);
		
		this.add(jt1);//把现有组件添加到窗体窗口
		this.add(jb);
		this.add(jt2); 
		
		this.setLocationRelativeTo(null);//窗口居中显示
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);	
		
		thread = new TimeNow();
		
		jb.addActionListener(new ButtonListener());
	}
	
	class TimeNow implements Runnable{
		public void run() {
			while(true) {
				jt1.setText(df.format(new Date()));
				try {
					Thread.sleep(1);
				}catch(InterruptedException e) {
					e.printStackTrace();
					System.exit(1);
				}
			}
		}

		public void start() {			
			jt2.setText(df.format(new Date()));
		}
	}
	
	class ButtonListener implements ActionListener{
		JPanel jp = new JPanel();

	    public void actionPerformed(ActionEvent e) {
			thread.start();
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值