首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java小程序,显示当前时间和每30秒更改一次的字符串

Java小程序,显示当前时间和每30秒更改一次的字符串
EN

Stack Overflow用户
提问于 2015-11-26 17:26:55
回答 1查看 330关注 0票数 1

此小程序显示时间和每隔30秒更改为另一个字符串的字符串,共有5个这样的字符串。

问题是在执行过程中,字符串并没有按照预期的那样改变。他们通常会跳过订单。

我想知道这种方法有什么问题?

代码语言:javascript
复制
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);


   }

}
EN

回答 1

Stack Overflow用户

发布于 2015-11-26 17:34:20

java Thread:: sleep (int毫秒)并没有在您传递给它的确切时间内休眠,相反,它休眠“至少毫秒”。重绘不会被调用来立即使你的视图失效。只要需要,它就会调用绘图。并且paint方法每秒可以被调用多次。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33934820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档