原始代碼存在多個關鍵問題:
package texttime;
import java.applet.*;
import java.util.*;
import java.awt.*;
public class TextTime extends Applet implements Runnable {
Thread th = null;
TextField tt = new TextField(30);
public void init() {
add(tt);
setLayout(new FlowLayout());
}
public void start() {
if (th == null) {
th = new Thread(this);
th.start();
}
}
public void stop() {
if (th != null) {
th.interrupt(); // 替代已過時的 stop()
th = null;
}
}
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Date dd = new Date();
tt.setText(dd.toString()); // 使用本地時間格式
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 保持中斷狀態
}
}
// 供測試用的 main 方法
public static void main(String[] args) {
Frame frame = new Frame("文字時鐘");
TextTime applet = new TextTime();
frame.add(applet);
frame.setSize(300, 100);
frame.setVisible(true);
applet.init();
applet.start();
}
}
使用 interrupt() 替代已棄用的 stop(),在 run() 中檢查 isInterrupted() 狀態優雅退出。
在 main 方法中創建 Frame 容器,手動調用 init() 和 start() 模擬 Applet 生命週期。
將 toGMTString() 改為 toString() 顯示本地時間,更符合用戶習慣。
考慮到 Applet 技術已過時,建議遷移至 Swing/JavaFX 實現桌面時鐘,或使用 JavaScript 實現 Web 版時鐘。