刚学习完线程部分,做个小练习。
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* 利用多线程制作电子时钟
* @作者: HK
*
* @date 2018-8-16 上午9:13:36
*/
public class Example07 extends JPanel implements Runnable{
/**
* 注意一点:刚开始是直接继承JFrame 的,后来实现一下,发现时间每秒重画一次比较闪。改成继承JPanel好多了。
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
JFrame frame = new JFrame();
Example07 th = new Example07();
frame.add(th);
frame.setTitle("电子时钟");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false); //窗口大小不变
frame.setVisible(true);
new Thread(th).start(); //开启线程
}
public void paint(Graphics g){
super.paint(g);
//设置字体大小
Font font = new Font("黑体", Font.BOLD, 50);
g.setFont(font);
g.setColor(Color.BLUE);//设置字体颜色
//格式时间, 画字体的位置
g.drawString(String.format("%tT", new Date()), 40, 75);
}
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
repaint();
}
}
}