java窗体程序秒表_利用所学的JAVA语言知识,完成一个实现秒表功能的程序,利用GUI界面设计: (1)在界面上方的...
时间: 2024-03-18 22:42:27 浏览: 15
好的,我可以帮助你完成这个任务。下面是一个简单的Java窗体程序秒表的实现示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Stopwatch extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel timeLabel;
private JButton startButton;
private JButton stopButton;
private JButton resetButton;
private Timer timer;
private int elapsedTime = 0;
public Stopwatch() {
setTitle("秒表");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
timeLabel = new JLabel("00:00:00.000", SwingConstants.CENTER);
timeLabel.setFont(new Font("Arial", Font.BOLD, 24));
contentPane.add(timeLabel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 3));
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);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
timer = new Timer(10, this);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == startButton) {
timer.start();
} else if (event.getSource() == stopButton) {
timer.stop();
} else if (event.getSource() == resetButton) {
timer.stop();
elapsedTime = 0;
updateDisplay();
} else if (event.getSource() == timer) {
elapsedTime += 10;
updateDisplay();
}
}
private void updateDisplay() {
int milliseconds = elapsedTime % 1000;
int seconds = (elapsedTime / 1000) % 60;
int minutes = (elapsedTime / (1000 * 60)) % 60;
int hours = (elapsedTime / (1000 * 60 * 60)) % 24;
String time = String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, milliseconds);
timeLabel.setText(time);
}
public static void main(String[] args) {
Stopwatch stopwatch = new Stopwatch();
stopwatch.setVisible(true);
}
}
```
这个程序使用了JFrame和JLabel等Swing组件来实现GUI界面设计,使用了Timer类来计时。用户可以通过点击“开始”按钮开始计时,点击“停止”按钮停止计时,点击“重置”按钮重置计时器。
在程序运行时,程序会显示一个窗口,包含一个显示时间的标签和三个按钮。标签初始显示为“00:00:00.000”。当用户点击“开始”按钮时,计时器开始计时,并且标签会显示实时的计时结果。当用户点击“停止”按钮时,计时器停止计时,并且标签显示最后的计时结果。当用户点击“重置”按钮时,计时器重置为初始状态,标签也会重新显示为“00:00:00.000”。