无法每秒更新时间
import java.awt.*;
import java.applet.*;
import java.util.*;
public class AppletClock extends Applet{
Calendar calendar;
Thread changeTime = null;
Thread changeBgColor = null;
String currentTime;
Color randomColor;
Font font = new Font("Arial",Font.BOLD+Font.ITALIC,80);
public void init(){
setBackground(Color.black);
setForeground(Color.WHITE);
changeTime = new Thread(new Runnable(){
public void run(){
for(;;){
calendar = Calendar.getInstance();/*When I Instantiate calendar object outside of for loop this code doesnot work and the time didnt gets updated every second Its because of this factory method or something else*/
currentTime = calendar.get(Calendar.HOUR) +":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND);
try{
Thread.sleep(1000);
}
catch(Exception e){
System.out.println(e);
}
repaint();
}
}
});
changeTime.start();
changeBgColor = new Thread(new Runnable(){
public void run(){
for(;;){
Random random = new Random();
int red = random.nextInt(255);
int green = random.nextInt(255);
int blue = random.nextInt(255);
randomColor = new Color(red,green,blue);
try{
Thread.sleep(1000);
}
catch(Exception e){
System.out.println(e);
}
repaint();
}
}
});
changeBgColor.start();
}
public void paint(Graphics g){
setBackground(randomColor);
g.setFont(font);
g.drawString(currentTime,80,120);
}
}
/*
<APPLET CODE = "AppletClock.class" WIDTH = 500 HEIGHT = 200></APPLET>
*/
当我在循环calendar
之外实例化对象时,for
此代码不起作用,并且时间不会每秒更新一次。这是因为这个工厂方法或其他原因