溫馨提示×

Java中怎么用swing實現鬧鐘

小億
127
2023-11-29 22:50:38
欄目: 編程語言

要使用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類獲取當前時間,并更新時間標簽的顯示。

這樣,一個簡單的鬧鐘程序就完成了??梢愿鶕枰砑悠渌M件和邏輯。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女