首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java Applet 文字時鐘運行異常的完整解決方案

     編輯:程式設計綜合問答

問題代碼分析

原始代碼存在多個關鍵問題:

  • 主方法 main 中未正確啟動 Applet 生命週期
  • Thread.stop() 方法已過時且不安全
  • 缺少 Applet 容器環境,無法直接作為獨立應用運行

修正後的完整代碼

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();
    }
}

關鍵修正點說明

1. 線程安全停止

使用 interrupt() 替代已棄用的 stop(),在 run() 中檢查 isInterrupted() 狀態優雅退出。

2. 獨立運行支持

在 main 方法中創建 Frame 容器,手動調用 init() 和 start() 模擬 Applet 生命週期。

3. 時間格式優化

將 toGMTString() 改為 toString() 顯示本地時間,更符合用戶習慣。

現代替代方案

考慮到 Applet 技術已過時,建議遷移至 Swing/JavaFX 實現桌面時鐘,或使用 JavaScript 實現 Web 版時鐘。

運行效果圖 用戶頭像
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved