java秒表计时器显示_Java实现的计时器【秒表】功能示例
时间: 2024-03-24 07:41:16 浏览: 148
以下是Java实现秒表计时器的示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Stopwatch implements ActionListener {
private JFrame frame;
private JLabel timeLabel;
private JButton startButton, stopButton, resetButton;
private Timer timer;
private int elapsedTime;
private int seconds;
private int minutes;
private int hours;
private boolean started;
public Stopwatch() {
frame = new JFrame("Stopwatch");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeLabel = new JLabel("00:00:00", JLabel.CENTER);
startButton = new JButton("Start");
stopButton = new JButton("Stop");
resetButton = new JButton("Reset");
startButton.addActionListener(this);
stopButton.addActionListener(this);
resetButton.addActionListener(this);
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
elapsedTime += 1000;
updateTimer();
}
});
JPanel panel = new JPanel(new GridLayout(2, 1));
JPanel topPanel = new JPanel(new GridLayout(1, 1));
JPanel bottomPanel = new JPanel(new GridLayout(1, 3));
topPanel.add(timeLabel);
bottomPanel.add(startButton);
bottomPanel.add(stopButton);
bottomPanel.add(resetButton);
panel.add(topPanel);
panel.add(bottomPanel);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new Stopwatch();
}
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() {
if (!started) {
started = true;
timer.start();
}
}
private void stop() {
if (started) {
started = false;
timer.stop();
}
}
private void reset() {
started = false;
timer.stop();
elapsedTime = 0;
seconds = 0;
minutes = 0;
hours = 0;
updateTimer();
}
private void updateTimer() {
seconds = (elapsedTime / 1000) % 60;
minutes = (elapsedTime / 60000) % 60;
hours = (elapsedTime / 3600000) % 24;
String secondsStr = String.format("%02d", seconds);
String minutesStr = String.format("%02d", minutes);
String hoursStr = String.format("%02d", hours);
timeLabel.setText(hoursStr + ":" + minutesStr + ":" + secondsStr);
}
}
```
这个示例代码实现了一个基本的秒表计时器功能,包括开始、停止和重置功能。它使用了Java Swing中的JFrame、JLabel、JButton和JPanel组件,以及Timer类来实现计时器的功能。当用户点击开始按钮时,计时器会开始计时;当用户点击停止按钮时,计时器会停止计时;当用户点击重置按钮时,计时器会重置为0。计时器的显示格式为:小时:分钟:秒钟。
阅读全文