极简版秒表(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();
}
}
}