📜  Java Applet-数字时钟(Digital Clock)

📅  最后修改于: 2020-10-01 04:20:05             🧑  作者: Mango

Applet中的数字时钟

可以使用Calendar和SimpleDateFormat类创建数字时钟。让我们看一个简单的例子:

Applet中的数字时钟示例:


import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;

public class DigitalClock extends Applet implements Runnable {

   Thread t = null;
   int hours=0, minutes=0, seconds=0;
   String timeString = "";

   public void init() {
      setBackground( Color.green);
   }

   public void start() {
        t = new Thread( this );
        t.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 date = cal.getTime();
            timeString = formatter.format( date );

            repaint();
            t.sleep( 1000 );  // interval given in milliseconds
         }
      }
      catch (Exception e) { }
   }

  
  public void paint( Graphics g ) {
      g.setColor( Color.blue );
      g.drawString( timeString, 50, 50 );
   }
}

在上面的示例中,MouseEvent的getX()和getY()方法用于获取当前的x轴和y轴。 Component类的getGraphics()方法返回Graphics的对象。

myapplet.html