java秒表计时器显示_Java实现的计时器【秒表】功能示例
时间: 2024-03-18 14:39:13 浏览: 14
以下是一个简单的Java实现的计时器(秒表)功能示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Stopwatch implements ActionListener {
JFrame frame;
JButton startButton, stopButton, resetButton;
JLabel timeLabel;
Timer timer;
int elapsedTime = 0;
int hours = 0, minutes = 0, seconds = 0, milliseconds = 0;
String hoursString, minutesString, secondsString, millisecondsString;
public Stopwatch() {
frame = new JFrame("Stopwatch");
frame.setSize(350, 200);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeLabel = new JLabel();
timeLabel.setFont(new Font("Arial", Font.PLAIN, 60));
timeLabel.setBounds(50, 50, 250, 50);
timeLabel.setHorizontalAlignment(JLabel.CENTER);
startButton = new JButton("Start");
startButton.setFont(new Font("Arial", Font.PLAIN, 20));
startButton.setBounds(50, 120, 80, 30);
startButton.addActionListener(this);
stopButton = new JButton("Stop");
stopButton.setFont(new Font("Arial", Font.PLAIN, 20));
stopButton.setBounds(140, 120, 80, 30);
stopButton.addActionListener(this);
resetButton = new JButton("Reset");
resetButton.setFont(new Font("Arial", Font.PLAIN, 20));
resetButton.setBounds(230, 120, 80, 30);
resetButton.addActionListener(this);
frame.add(timeLabel);
frame.add(startButton);
frame.add(stopButton);
frame.add(resetButton);
frame.setVisible(true);
}
public static void main(String[] args) {
new Stopwatch();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
start();
} else if (e.getSource() == stopButton) {
stop();
} else if (e.getSource() == resetButton) {
reset();
}
}
private void start() {
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
elapsedTime += 10;
hours = (elapsedTime / 3600000);
minutes = (elapsedTime / 60000) % 60;
seconds = (elapsedTime / 1000) % 60;
milliseconds = elapsedTime % 1000;
hoursString = String.format("%02d", hours);
minutesString = String.format("%02d", minutes);
secondsString = String.format("%02d", seconds);
millisecondsString = String.format("%03d", milliseconds);
timeLabel.setText(hoursString + ":" + minutesString + ":" + secondsString + ":" + millisecondsString);
}
});
timer.start();
}
private void stop() {
timer.stop();
}
private void reset() {
timer.stop();
elapsedTime = 0;
hours = 0;
minutes = 0;
seconds = 0;
milliseconds = 0;
hoursString = "00";
minutesString = "00";
secondsString = "00";
millisecondsString = "000";
timeLabel.setText(hoursString + ":" + minutesString + ":" + secondsString + ":" + millisecondsString);
}
}
```
该程序利用了Swing图形用户界面库来创建一个窗口,并在其中添加了一个标签、三个按钮和一个计时器。计时器每10毫秒更新一次标签,以显示经过的时间。用户可以通过单击“Start”按钮启动计时器,通过单击“Stop”按钮停止计时器,并通过单击“Reset”按钮重置计时器。