Java 数字时钟

package cn.com.threan;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

import com.sun.org.apache.bcel.internal.generic.NEW;

public class TimeDemo extends JFrame implements Runnable, ActionListener {

 private JLabel timeLabel;

 private String timeString;

 private SimpleDateFormat format;

 public TimeDemo() {
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  TimeDemo demo = new TimeDemo();
  demo.init();
  // 通过线程来显示时钟
  Thread tt = new Thread(demo);
  tt.start();
  // 通过定时器来显示时钟
  // Timer timer = new Timer(1000,demo);
  // timer.start();
 }

 public void run() {
  while (true) {

   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println(new Date());
   timeLabel.setText(format.format(new Date()));
  }
 }

 /**
  * 初始化窗体
  */
 public void init() {
  this.setTitle("时钟");
  this.setSize(200, 100);
  // this.setBackground(Color.PINK);
  this.setLocationRelativeTo(null);
  format = new SimpleDateFormat("hh:mm:ss");
  this.add(creatLabel());
  // TimeDemo t = new TimeDemo();

  this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
  this.setVisible(true);
 }

 /**
  * 创建标签
  * @return
  */
 public JLabel creatLabel() {
  Date date = new Date();

  timeString = format.format(date);
  timeLabel = new JLabel(timeString, JLabel.CENTER);
  timeLabel.setFont(new Font("华文行楷", Font.BOLD, 40));
  timeLabel.setForeground(Color.BLUE);
  return timeLabel;
 }

 public void actionPerformed(ActionEvent e) {
  timeLabel.setText(format.format(new Date()));
 }

}

你可能感兴趣的:(java,apache,thread,swing,sun)