netbeans 中的时间不会动态变化

time not changing dynamically in netbeans

如果我删除 final,它会在使用日历变量时出错,而在使用 final 时间时不会动态变化

final Calendar cal= new GregorianCalendar();
     Thread clock= new Thread(){
     public void run(){
      for (;;) {
        int am=cal.get(Calendar.AM_PM);
        int hr=cal.get(Calendar.HOUR);
        int min=cal.get(Calendar.MINUTE);
        int sec=cal.get(Calendar.SECOND);
         if (am==0) {
             jtime_Label.setText(""+hr+":"+min+":"+sec+" AM");
         }else
         {
         jtime_Label.setText(""+hr+":"+min+":"+sec+" PM");
         }
         int day=cal.get(Calendar.DAY_OF_MONTH);
     int mon=cal.get(Calendar.MONTH);
     int year=cal.get(Calendar.YEAR);
     date_label.setText(""+day+"-"+(mon+1)+"-"+year);

    }

     }


     };
     clock.start();

if i remove final it gives error while using calendar variable !!

一点也不奇怪,因为JLS指定了所以会报错

However, a local class can only access local variables that are declared final

Java Docs所说

public GregorianCalendar() //---> Default constructor

Constructs a default GregorianCalendar using the current time in the default time zone with the default locale

所以这并不意味着如果您要在 10 分钟后或 20 分钟后使用此日历对象,它会更改时间,对象创建后时间将保持不变

如果您想创建一个计时器,那么 JTimer 可能会帮助您,但这不是正确的方法!!

您已经创建了一个 GregorianCalendar 对象,该对象将在创建时显示当前时间。

在处理从中读取时间时,您不要更改该时间 您需要在处理过程中更改日历中的时间。

我建议添加

cal.setTime(new Date());

cal.setTimeInMillis(System.currentTimeMillis());

在线程中的循环中。

像这样

final Calendar cal= new GregorianCalendar();
Thread clock= new Thread(){
public void run(){
    for (;;) {
        //// add this line
        cal.setTimeInMillis(System.currentTimeMillis());
        /////
        int am=cal.get(Calendar.AM_PM);
        int hr=cal.get(Calendar.HOUR);
        int min=cal.get(Calendar.MINUTE);
        int sec=cal.get(Calendar.SECOND);
        if (am==0) {
            jtime_Label.setText(""+hr+":"+min+":"+sec+" AM");
        } else {
            jtime_Label.setText(""+hr+":"+min+":"+sec+" PM");
        }
        int day=cal.get(Calendar.DAY_OF_MONTH);
        int mon=cal.get(Calendar.MONTH);
        int year=cal.get(Calendar.YEAR);
        date_label.setText(""+day+"-"+(mon+1)+"-"+year);
        }
    }
};
clock.start();