设计StopWatch APP。单击“Start”按钮,计时器开始工作,单击“Stop”按钮,计时器停止工作,单击“Reset”按钮,计时器复位。当计时器界面未获得焦点时暂停工作;当计时器重新获得焦点时继续工作的代码
时间: 2023-05-20 19:04:11 浏览: 32
以下是一个简单的 StopWatch APP 的设计,使用 Java 语言编写:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StopWatch extends JFrame implements ActionListener {
private JLabel timeLabel;
private JButton startButton, stopButton, resetButton;
private Timer timer;
private int elapsedTime = 0;
public StopWatch() {
setTitle("StopWatch");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeLabel = new JLabel("00:00:00", SwingConstants.CENTER);
timeLabel.setFont(new Font("Arial", Font.PLAIN, 50));
add(timeLabel, BorderLayout.CENTER);
startButton = new JButton("Start");
startButton.addActionListener(this);
stopButton = new JButton("Stop");
stopButton.addActionListener(this);
resetButton = new JButton("Reset");
resetButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
buttonPanel.add(resetButton);
add(buttonPanel, BorderLayout.SOUTH);
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
elapsedTime++;
updateTimeLabel();
}
});
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
timer.start();
} else if (e.getSource() == stopButton) {
timer.stop();
} else if (e.getSource() == resetButton) {
elapsedTime = 0;
updateTimeLabel();
}
}
private void updateTimeLabel() {
int hours = elapsedTime / 3600;
int minutes = (elapsedTime % 3600) / 60;
int seconds = elapsedTime % 60;
timeLabel.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
public static void main(String[] args) {
StopWatch stopWatch = new StopWatch();
stopWatch.setVisible(true);
}
}
```
这个 APP 使用了一个计时器(`Timer`)来实现计时功能,每秒钟更新一次计时器的显示。当用户单击“Start”按钮时,计时器开始工作;当用户单击“Stop”按钮时,计时器停止工作;当用户单击“Reset”按钮时,计时器复位。当计时器界面未获得焦点时暂停工作,当计时器重新获得焦点时继续工作。