Java 示例 - 使用 Applet 显示时钟?

  • 问题描述

    如何使用 Applet 显示时钟?
  • 解决方案

    以下示例演示如何使用 String 类的 valueOf() 方法显示时钟。& 使用 Calender 类来获取秒、分钟和小时。
    
    import java.awt.*;
    import java.applet.*;
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    public class ClockApplet extends Applet implements Runnable { 
       Thread t,t1;
       public void start() {
          t = new Thread(this);
          t.start();
       }
       public void run() { 
          t1 = Thread.currentThread();
          while(t1 == t) {
             repaint();
             try {
                t1.sleep(1000);    
             }
             catch(InterruptedException e){}
          }
       }
       public void paint(Graphics g) {
          Calendar cal = new GregorianCalendar();
          String hour = String.valueOf(cal.get(Calendar.HOUR));
          String minute = String.valueOf(cal.get(Calendar.MINUTE));
          String second = String.valueOf(cal.get(Calendar.SECOND));
          g.drawString(hour + ":" + minute + ":" + second, 20, 30);
       }
    }
    
  • 结果

    上面的代码示例将在启用 java 的 Web 浏览器中产生以下结果。
    
    View in Browser. 
    
    下面是另一个使用 Applet 显示时钟的示例。
    
    import java.applet.*;  
    import java.awt.*;  
    import java.util.*;  
    import java.text.*;  
      
    public class javaApplication6 extends Applet implements Runnable {  
       Thread t1 = null;  
       int hours = 0, minutes = 0, seconds = 0;
       String time = "";
       
       public void init() {  
          setBackground( Color.green);  
       }  
       public void start() {
          t1 = new Thread( this );
          t1.start();
       } 
       public void run() {
          try {
             while (true) {
                Calendar cal = Calendar.getInstance();  
                hours = cal.get( Calendar.HOUR_OF_DAY );  
                if ( hours > 12 ) hours -= 12;  
                minutes = cal.get( Calendar.MINUTE );  
                seconds = cal.get( Calendar.SECOND );
                
                SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");  
                Date d = cal.getTime();  
                time = formatter.format( d );
                
                repaint();  
                t1.sleep( 1000 ); 
             }  
          }  
          catch (Exception e) { }  
       } 
       public void paint( Graphics g ) {
          g.setColor( Color.blue );  
          g.drawString( time, 50, 50 );  
       }  
    }