演示图
非常质朴的时钟
一、界面设计
JFrame app=new JFrame("电子闹钟");
Container c=app.getContentPane(); //设置一个面板容器 面板为初始设置面板
JLabel clock=new JLabel("电子闹钟");
clock.setHorizontalTextPosition(JLabel.CENTER); //设置标题水平对齐方式 水平放在中央
c.setLayout(new BorderLayout());
clock.setFont(new Font("微软雅黑", Font.BOLD, 30));
c.add(clock,BorderLayout.CENTER);
app.setSize(400,160);
app.setLocation(600,300);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
一个非常简单的显示界面
二、获取时间与设置时间
class MyThread extends Thread{
private JLabel clock;
public MyThread(JLabel clock){
this.clock=clock;
}
public void run(){
while (true){
clock.setText(this.getTime());
}
}
public String getTime(){
Date day=new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(day);
}
三、完整代码
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Clock {
public Clock(){
JFrame app=new JFrame("电子闹钟");
Container c=app.getContentPane(); //设置一个面板容器 面板为初始设置面板
JLabel clock=new JLabel("电子闹钟");
clock.setHorizontalTextPosition(JLabel.CENTER); //设置标题水平对齐方式 水平放在中央
c.setLayout(new BorderLayout());
clock.setFont(new Font("微软雅黑", Font.BOLD, 30));
c.add(clock,BorderLayout.CENTER);
app.setSize(400,160);
app.setLocation(600,300);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
Thread t=new MyThread(clock);
t.start();
}
class MyThread extends Thread{
private JLabel clock;
public MyThread(JLabel clock){
this.clock=clock;
}
public void run(){
while (true){
clock.setText(this.getTime());
}
}
public String getTime(){
Date day=new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(day);
}
}
public static void main(String[] args) {
new Clock();
}
}