使用java编写一个计时器
时间: 2024-05-14 11:18:34 浏览: 76
java代码-使用java制作一个计时器的源代码
以下是一个简单的计时器示例,使用Java编写:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TimerExample extends JFrame {
private Timer timer;
private int seconds = 0;
private JLabel label;
public TimerExample() {
setTitle("计时器");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
label = new JLabel("计时器:00:00:00");
label.setFont(new Font("Arial", Font.BOLD, 24));
label.setHorizontalAlignment(SwingConstants.CENTER);
add(label, BorderLayout.CENTER);
JButton startButton = new JButton("开始");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start();
}
});
add(startButton, BorderLayout.NORTH);
JButton stopButton = new JButton("停止");
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stop();
}
});
add(stopButton, BorderLayout.SOUTH);
}
private void start() {
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
seconds++;
int hour = seconds / 3600;
int minute = (seconds % 3600) / 60;
int second = seconds % 60;
String time = String.format("%02d:%02d:%02d", hour, minute, second);
label.setText("计时器:" + time);
}
});
timer.start();
}
private void stop() {
if (timer != null) {
timer.stop();
timer = null;
}
seconds = 0;
label.setText("计时器:00:00:00");
}
public static void main(String[] args) {
TimerExample timerExample = new TimerExample();
timerExample.setVisible(true);
}
}
```
该程序创建一个带有“开始”和“停止”按钮的窗口,当用户单击“开始”按钮时,计时器将开始计时,并且计时器标签将更新以显示经过的时间。当用户单击“停止”按钮时,计时器将停止并将时间重置为零。
阅读全文