java 钟_java实现时钟效果
时间: 2023-10-17 17:22:07 浏览: 47
要实现一个时钟效果,可以使用 Java 中的 Swing 组件库。下面是一个简单的 Java 时钟实现:
```java
import java.awt.Font;
import java.awt.Graphics;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Clock extends JPanel implements Runnable {
private Thread thread;
private Font clockFont;
private SimpleDateFormat timeFormat;
public Clock() {
this.clockFont = new Font("Arial", Font.BOLD, 48);
this.timeFormat = new SimpleDateFormat("HH:mm:ss");
this.thread = new Thread(this);
this.thread.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
Calendar calendar = Calendar.getInstance();
String time = this.timeFormat.format(calendar.getTime());
g.setFont(this.clockFont);
g.drawString(time, 100, 100);
}
@Override
public void run() {
while (true) {
this.repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Java Clock");
Clock clock = new Clock();
frame.add(clock);
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
在这个例子中,我们使用了 JPanel 组件来绘制时钟,并且使用了 Thread 来更新时钟。在 run 方法中,我们使用了 Thread.sleep(1000) 来让线程休眠 1 秒钟,以保证时钟每秒钟更新一次。最后,我们将 JPanel 组件添加到 JFrame 中,并设置 JFrame 的大小和关闭操作。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)