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

标签 java applet

这个小程序显示时间和一个每 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) 并没有在您传递给它的确切时间内 hibernate ,而是 hibernate “至少毫秒”。 并且不会调用 repaint 来立即使您的 View 无效。它可以随时调用paint。 并且paint方法每秒可以调用多次。

关于Java Applet,显示当前时间和每 30 秒更改一次的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33934820/

相关文章:

java - PayPal 卖家沙盒账户 - 为什么我看不到任何交易?

java - 如何使用Java代码删除日志文件的内容

java - 在 Applet 中加载 ActiveX 对象

java - 小程序可以从小程序标签授予权限吗

java - 如何将Java程序转换为Applet?

java - 如何将在 Eclipse 中制作的小程序变成可以在 Web 浏览器中运行的程序?

java - 更改 DefaultMutableTreeNode 的文本样式

java - Android 应用程序黑屏( onCreate() )

java - 保存Applet中生成的文件

java - vector 中以给定字母/数字开头的元素