簡體   English   中英

Java Applet,顯示當前時間和每30秒更改一次的字符串

[英]Java Applet, Displaying current time and String that changes every 30 seconds

此小程序顯示時間和一個字符串,該字符串每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);


   }

}

java Thread :: sleep(int millisecond)在您傳遞給它的確切時間內沒有進入睡眠狀態,而是睡眠了“至少毫秒”。 並沒有調用重畫立即使您的視圖無效。 它會在需要時調用繪畫。 而且paint方法可以每秒調用多次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM