Java写一个计时器窗口,打开就运行
时间: 2024-03-06 19:49:36 浏览: 16
好的,以下是一个简单的Java计时器窗口的示例代码,它会在窗口打开时自动开始计时:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TimerWindow extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel timeLabel;
private Timer timer;
private int timeCount = 0;
private JButton startButton, stopButton, resetButton;
public TimerWindow() {
setTitle("计时器");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeLabel = new JLabel("00:00:00");
timeLabel.setFont(new Font("宋体", Font.PLAIN, 50));
timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(timeLabel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
startButton = new JButton("开始");
startButton.addActionListener(this);
buttonPanel.add(startButton);
stopButton = new JButton("暂停");
stopButton.addActionListener(this);
buttonPanel.add(stopButton);
resetButton = new JButton("重置");
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
add(buttonPanel, BorderLayout.SOUTH);
// 自动启动计时器
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
timeCount++;
int hour = timeCount / 3600;
int minute = (timeCount - hour * 3600) / 60;
int second = timeCount - hour * 3600 - minute * 60;
timeLabel.setText(String.format("%02d:%02d:%02d", hour, minute, second));
}
});
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
timer.start();
} else if (e.getSource() == stopButton) {
timer.stop();
} else if (e.getSource() == resetButton) {
timeCount = 0;
timeLabel.setText("00:00:00");
timer.stop();
}
}
public static void main(String[] args) {
TimerWindow frame = new TimerWindow();
frame.setVisible(true);
}
}
```
这个计时器窗口与之前的示例相似,唯一的区别是它在构造函数中自动启动了计时器。注意,当窗口关闭时,计时器也会停止。