Java中怎么用swing实现闹钟

avatar
作者
筋斗云
阅读量:0

要使用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类获取当前时间,并更新时间标签的显示。

这样,一个简单的闹钟程序就完成了。可以根据需要添加其他组件和逻辑。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!