共計 1322 個字符,預計需要花費 4 分鐘才能閱讀完成。
要使用 Swing 實現一個簡單的鬧鐘,可以按照以下步驟進行:
- 創建一個繼承自 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();}
});
}
}
- 在 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();}
});
}
}
- 使用 Swing 的 Timer 類,每秒鐘更新一次時間。在更新時間的方法中,通過 SimpleDateFormat 類獲取當前時間,并更新時間標簽的顯示。
這樣,一個簡單的鬧鐘程序就完成了。可以根據需要添加其他組件和邏輯。
丸趣 TV 網 – 提供最優質的資源集合!
正文完