久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

Java中怎么用swing實現鬧鐘

143次閱讀
沒有評論

共計 1322 個字符,預計需要花費 4 分鐘才能閱讀完成。

要使用 Swing 實現一個簡單的鬧鐘,可以按照以下步驟進行:

  1. 創建一個繼承自 JFrame 的主窗口類 ClockFrame。
import javax.swing.*;

public class ClockFrame extends JFrame {public ClockFrame() {setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setTitle(" 鬧鐘 ");
        setLocationRelativeTo(null); // 將窗口居中顯示 

        // TODO: 添加其他組件和邏輯 

        setVisible(true);
    }

    public static void main(String[] args) {SwingUtilities.invokeLater(new Runnable() {@Override
            public void run() {new ClockFrame();}
        });
    }
}
  1. 在 ClockFrame 類中添加一個 JLabel 組件用于顯示當前時間。
import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClockFrame extends JFrame {private JLabel timeLabel;

    public ClockFrame() {setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setTitle(" 鬧鐘 ");
        setLocationRelativeTo(null); // 將窗口居中顯示 

        timeLabel = new JLabel();
        timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        updateTime();

        getContentPane().add(timeLabel);

        setVisible(true);
    }

    private void updateTime() {SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String timeStr = sdf.format(new Date());
        timeLabel.setText(timeStr);

        // 每秒鐘更新一次時間 
        Timer timer = new Timer(1000, e -> updateTime());
        timer.setRepeats(true);
        timer.start();}

    public static void main(String[] args) {SwingUtilities.invokeLater(new Runnable() {@Override
            public void run() {new ClockFrame();}
        });
    }
}
  1. 使用 Swing 的 Timer 類,每秒鐘更新一次時間。在更新時間的方法中,通過 SimpleDateFormat 類獲取當前時間,并更新時間標簽的顯示。

這樣,一個簡單的鬧鐘程序就完成了。可以根據需要添加其他組件和邏輯。

丸趣 TV 網 – 提供最優質的資源集合!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2023-12-09發表,共計1322字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 久治县| 鸡泽县| 阿城市| 会宁县| 凤山市| 寿宁县| 双峰县| 岳西县| 玉环县| 阿勒泰市| 华容县| 金湖县| 崇信县| 太康县| 杂多县| 塔河县| 灵川县| 抚宁县| 肥东县| 涟源市| 上思县| 六枝特区| 纳雍县| 广安市| 囊谦县| 监利县| 喀喇| 贵溪市| 庆城县| 和田县| 宽城| 布拖县| 巴南区| 三亚市| 西畴县| 桂平市| 涟源市| 沁源县| 博乐市| 宁阳县| 灵石县|