《java简易电子时钟代码》由会员分享,可在线阅读,更多相关《java简易电子时钟代码(3页珍藏版)》请在金锄头文库上搜索。
1、import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; import java.text.SimpleDateFormat; publicclass ClockJFrame extends JFrame private Date now=new Date(); Panel buttons=new Panel(); Button button_start=new Button(“ 启动 “ ); Button button_interrupt=new Button(“ 停止 “ )
2、; 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); b
3、uttons.setLayout(new FlowLayout(); buttons.add(button_start); buttons.add(button_interrupt); setVisible(true ); privateclass Clock extends Label implements ActionListener,Runnable private Thread clocker=null; private Date now=new Date(); public Clock() button_start.addActionListener(this); button_in
4、terrupt.addActionListener(this); SimpleDateFormat dateFormat = new SimpleDateFormat(“HH:mm:ss“); / 可以方便地修改日期格式String t = dateFormat.format( now ); this.setText(t); publicvoid start() if ( clocker=null) clocker=new Thread(this); clocker.start(); publicvoid stop() clocker=null; publicvoid run() Thread
5、 currentThread=Thread.currentThread(); while( clocker=currentThread) now=new Date(); SimpleDateFormat dateFormat = newSimpleDateFormat(“HH:mm:ss“); / 可以方便地修改日期格式String t = dateFormat.format( now ); this.setText(t); try clocker. sleep (1000); catch (InterruptedException ie) JOptionPane.showMessageDia
6、log( this, “Thread error:+ie“); publicvoid 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); / 内部类结束publicstaticvoid main(String args) ClockJFrame time=new ClockJFrame(); 运行结果: