当前位置:文档之家› java简易电子时钟代码

java简易电子时钟代码

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.SimpleDateFormat;
public class ClockJFrame extends JFrame{
private Date now=new Date();
Panel buttons=new Panel();
Button button_start=new Button("启动");
Button button_interrupt=new Button("停止");
Clock label=new Clock();
public ClockJFrame() //构造方法
{
super("电子时钟");
this.setBounds(300,240,300,120);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.getContentPane().add("North",label);//初始化一个容器,用来在容器上添加一个标签
this.getContentPane().add("South",buttons);
buttons.setLayout(new FlowLayout());
buttons.add(button_start);
buttons.add(button_interrupt);
setVisible(true);
}
private class Clock extends Label implements ActionListener,Runnable{ private Thread clocker=null;
private Date now=new Date();
public Clock(){
button_start.addActionListener(this);
button_interrupt.addActionListener(this);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");//可以方便地修改日期格式
String t = dateFormat.format( now );
this.setText(t);
}
public void start(){
if(clocker==null){
clocker=new Thread(this);
clocker.start();
}
}
public void stop(){
clocker=null;
}
public void run(){
Thread currentThread=Thread.currentThread();
while(clocker==currentThread){
now=new Date();
SimpleDateFormat dateFormat = new
SimpleDateFormat("HH:mm:ss");//可以方便地修改日期格式
String t = dateFormat.format( now );
this.setText(t);
try{
clocker.sleep(1000);
}catch(InterruptedException ie){
JOptionPane.showMessageDialog(this,"Thread error:+ie");
}
}
}
public void actionPerformed(ActionEvent e){
if (e.getSource()==button_start) {
clocker = new Thread(this); //重新创建一个线程对象
clocker.start();
button_start.setEnabled(false);
button_interrupt.setEnabled(true);
}
if (e.getSource()==button_interrupt) //单击中断按钮时
{
clocker.stop(); //设置当前线程对象停止标记
button_start.setEnabled(true);
button_interrupt.setEnabled(false);
}
}
}//内部类结束
public static void main(String[] args) {
ClockJFrame time=new ClockJFrame();
}
}
运行结果:。

相关主题