此小程序显示时间和每隔30秒更改为另一个字符串的字符串,共有5个这样的字符串。
问题是在执行过程中,字符串并没有按照预期的那样改变。他们通常会跳过订单。
我想知道这种方法有什么问题?
package applet;
import java.applet.Applet;
import java.awt.Graphics;
import java.text.SimpleDateFormat;
import java.util.*;
public class Project1 extends Applet implements Runnable {
String[] str = new String[4];
int index=0;
private static final long serialVersionUID = 1L;
Thread t,t1;
public void start(){
setSize(getMaximumSize());
t = new Thread(this);
t.start();
str[0] = "Hope for the best, but prepare for the worst.";
str[1] = "You can't judge a book by its cover.";
str[2] = "Do unto others as you would have them do unto you.";
str[3] = "Practice makes perfect.";
}
public void run(){
t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
int sec = cal.get(Calendar.SECOND);
if(sec ==30 ||sec == 60){
++index;
}
if(index > 4) index =0;
g.drawString(str[index], 400, 300);
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm.ss aa");
String formattedDate = dateFormat.format(new Date()).toString();
g.drawString(formattedDate,800,30);
g.drawString("Counter: " + (index+1), 600, 400);
}
}
发布于 2015-11-26 17:34:20
java Thread:: sleep (int毫秒)并没有在您传递给它的确切时间内休眠,相反,它休眠“至少毫秒”。重绘不会被调用来立即使你的视图失效。只要需要,它就会调用绘图。并且paint方法每秒可以被调用多次。
https://stackoverflow.com/questions/33934820
复制相似问题