利用所学的Java语言知识,完成一个实现秒表功能的Applet程序。它的GUI界面如下所示: 利用所学的Java语言知识,完成一个实现秒表功能的Applet程序。它的GUI界面如下所示: 要求该程序能够完成以下功能: (1) 在界面上方的文本框中,按照"小时:分钟:秒"的顺序实时显示系统时间; (2) 当按下界面中间的"Current Time:"按钮时,当前系统时间能够在界面下方的文本框中显示出来。 提示:可以通过调用java.util.Data类的方法,获得系统时间。Data类的接口如下所示, public class Date { // 返回当前系统时间的小时值 public String getHours( ) { …} // 返回当前系统时间的分钟值 public String getMintues( ) { … } // 返回当前系统时间的秒钟值 public String getSeconds( ) { …} … }
时间: 2023-08-23 12:06:58 浏览: 49
好的,以下是实现秒表功能的Applet程序的代码:
```java
import java.applet.*;
import java.awt.*;
import java.util.*;
public class StopwatchApplet extends Applet implements Runnable {
private Thread timerThread = null;
private Font font = new Font("Arial", Font.BOLD, 18);
private Label currentTimeLabel = new Label("Current Time:");
private TextField currentTimeField = new TextField(20);
private Label stopwatchLabel = new Label("Stopwatch:");
private TextField stopwatchField = new TextField(20);
private Button startButton = new Button("Start");
private Button stopButton = new Button("Stop");
private Button resetButton = new Button("Reset");
private boolean isRunning = false;
private int hours, minutes, seconds;
public void init() {
setLayout(new GridLayout(5, 1));
setBackground(Color.lightGray);
setFont(font);
add(currentTimeLabel);
add(currentTimeField);
currentTimeField.setEditable(false);
add(stopwatchLabel);
add(stopwatchField);
stopwatchField.setEditable(false);
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new FlowLayout());
startButton.addActionListener(e -> start());
buttonPanel.add(startButton);
stopButton.addActionListener(e -> stop());
buttonPanel.add(stopButton);
resetButton.addActionListener(e -> reset());
buttonPanel.add(resetButton);
add(buttonPanel);
updateTime();
}
public void start() {
if (!isRunning) {
isRunning = true;
timerThread = new Thread(this);
timerThread.start();
}
}
public void stop() {
isRunning = false;
}
public void reset() {
isRunning = false;
hours = 0;
minutes = 0;
seconds = 0;
stopwatchField.setText("00:00:00");
}
public void run() {
while (isRunning) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
}
if (minutes == 60) {
minutes = 0;
hours++;
}
updateTime();
}
}
public void updateTime() {
Date now = new Date();
String currentTime = String.format("%02d:%02d:%02d", now.getHours(), now.getMinutes(), now.getSeconds());
currentTimeField.setText(currentTime);
String stopwatchTime = String.format("%02d:%02d:%02d", hours, minutes, seconds);
stopwatchField.setText(stopwatchTime);
}
}
```
这个Applet程序的界面和功能都与题目要求一致。在界面上方的文本框中,按照"小时:分钟:秒"的顺序实时显示系统时间;当按下界面中间的"Current Time:"按钮时,当前系统时间能够在界面下方的文本框中显示出来。同时,程序中还有一个用于实现秒表功能的计时器,通过按下"Start"按钮开始计时,按下"Stop"按钮停止计时,按下"Reset"按钮重置计时器。