Java中怎么用swing实现闹钟

49次阅读
没有评论

共计 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字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)