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();
}
}
03-20
2106

01-03