【问题标题】:Slow populating of Java JFrame Application with NetBeans 11.0使用 NetBeans 11.0 缓慢填充 Java JFrame 应用程序
【发布时间】:2019-10-16 09:58:41
【问题描述】:

我正在学习 Java,所以我从创建一个数字时钟 JFrame 表单开始。一切正常,但在加载应用程序后,大约需要 2/3 秒才能在背景面板上显示我的边框和标签。

文件:DigitalClock.java

package digitalclock;

import JForms.DigitalClockJForm;

public class DigitalClock {

    public static void main(String[] args) {
        new DigitalClockJForm().setVisible(true);

    }

}

文件:DigitalClockJForm.java

package JForms;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DigitalClockJForm extends javax.swing.JFrame 
{   
    // Member Variables
    private int second, minute, hour, day, month, year;
    String timeDate;

    // Constructors
    public DigitalClockJForm() {
        initComponents();
        clock();
    }

    public void clock()
    {
        Thread t = new Thread(){

            @Override
            public void run(){

                try {
                    while (true){
                        Calendar cal = new GregorianCalendar();

                        day = cal.get(Calendar.DAY_OF_MONTH);
                        month = cal.get(Calendar.MONTH);
                        year = cal.get(Calendar.YEAR);

                        second = cal.get(Calendar.SECOND);
                        minute = cal.get(Calendar.MINUTE);
                        hour = cal.get(Calendar.HOUR);

                        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a dd/MM/yyyy");

                        Date date = cal.getTime();

                        timeDate = sdf.format(date);

                        mainLabel.setText(timeDate);
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        t.start();
    }

 << Net Beans generated code >>

// Variables declaration - do not modify                     
private javax.swing.JLabel mainLabel;
private javax.swing.JPanel mainPanel;
// End of variables declaration   

标签和面板需要 2/3 秒才能显示在表单上。

表单启动如下:

然后在 2/3 秒后,包括边框在内的所有内容都正确显示:

我希望标签和面板会在应用程序启动后立即显示。

【问题讨论】:

  • 1) 不要使用while (true)utils.Timer,而是使用Swing Timer 来更新用户界面。 2) 也不要扩展JFrame。您的问题更有可能是因为第一点。但是为了获得更好的帮助,请尽快发布正确的minimal reproducible example
  • 请参阅:stackoverflow.com/questions/7816585/…,了解使用 Swing Timer 的示例。

标签: java swing jframe designer


【解决方案1】:

没有必要继承 JFrame,甚至 JPanel 在你的情况下,因为你没有覆盖他们的任何方法。 只需创建一个 JPanel 并将您的组件添加到其中,然后将该 JPanel 添加到新的 JFrame,打包框架并显示它。

创建一个具有 1000 毫秒延迟的 Swing.Timer,并在 actionPerformed 方法中更新显示的时间。

每次调用 actionPerformed 方法时创建一个新的 GregorianCalendar 可能有点过头了。每次将显示更新一秒就足够了,也许每隔几分钟就有一个新的日历重新同步,除非您的 CPU 非常忙于执行其他应用程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2011-01-06
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多