如何使用Applet显示时钟?(How to display clock using Applet?)
优质
小牛编辑
126浏览
2023-12-01
问题描述 (Problem Description)
如何使用Applet显示时钟?
解决方案 (Solution)
下面的示例演示如何使用String Class的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);
}
}
结果 (Result)
上面的代码示例将在启用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 );
}
}