java实现秒表计时器

本文介绍了使用JavaSwing库创建一个简单的计时器Stopwatch类,包括启动、停止计时和显示时间的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

public class Stopwatch implements Runnable {
   
private Thread thread;
   
private boolean isRunning = false;
   
private long startTime;
   
private long pauseTime;
   
private long pauseCount;

   
private JFrame frame;
   
private JLabel timeLabel;
   
private JButton startButton;
   
private JButton stopButton;

   
public Stopwatch() {
       
frame = new JFrame("Stopwatch");
       
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
frame.setSize(300, 200);
       
frame.setLayout(new BorderLayout());

       
timeLabel = new JLabel("00:00:00.0", SwingConstants.CENTER);
       
timeLabel.setFont(new Font("Arial", Font.PLAIN, 50));
       
frame.add(timeLabel, BorderLayout.CENTER);

       
startButton = new JButton("Start");
       
startButton.addActionListener(new ActionListener() {
           
public void actionPerformed(ActionEvent e) {
                start();
            }
        });
       
frame.add(startButton, BorderLayout.NORTH);

       
stopButton = new JButton("Stop");
       
stopButton.addActionListener(new ActionListener() {
            
public void actionPerformed(ActionEvent e) {
                stop();
            }
        });
       
frame.add(stopButton, BorderLayout.SOUTH);

       
frame.setVisible(true);
    }

   
public void start() {
       
if (!isRunning) {
           
isRunning = true;
           
startTime = System.currentTimeMillis();
           
thread = new Thread(this);
           
thread.start();
        }
    }

   
public void stop() {
       
if (isRunning) {
           
isRunning = false;
           
pauseTime = System.currentTimeMillis();
           
pauseCount += (pauseTime - startTime);
        }
    }

   
public void run() {
       
while (isRunning) {
           
long elapsedTime = System.currentTimeMillis() - startTime - pauseCount;
           
int hours = (int) (elapsedTime / 3600000);
           
int minutes = (int) ((elapsedTime - hours * 3600000) / 60000);
           
int seconds = (int) ((elapsedTime - hours * 3600000 - minutes * 60000) / 1000);
           
int tenths = (int) ((elapsedTime - hours * 3600000 - minutes * 60000 - seconds * 1000) / 100);
           
timeLabel.setText(String.format("%02d:%02d:%02d.%d", hours, minutes, seconds, tenths));
           
try {
               
Thread.sleep(100);
            }
catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值