簡體   English   中英

使用NetBeans 11.0緩慢填充Java JFrame應用程序

[英]Slow populating of Java JFrame Application with NetBeans 11.0

我正在學習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秒才能在表單上顯示。

表單啟動如下: 圖01:啟動應用程序時

然后在2/3秒后,包括邊框在內的所有內容都會正確顯示: 圖01:表格在2/3秒后看起來正確

我希望在應用程序啟動后立即顯示標簽和面板。

在您的情況下,不需要為JFrame,甚至JPanel創建子類,因為您沒有覆蓋任何方法。 只需創建一個JPanel並將組件添加到它,然后將該JPanel添加到新的JFrame,打包框架並顯示它。

創建一個延遲1000毫秒的Swing.Timer,並在actionPerformed方法中更新顯示的時間。

每次調用actionPerformed方法時創建一個新的GregorianCalendar可能有點過分。 每次更新顯示一秒鍾就足夠了,可能需要每隔幾分鍾使用一個新的日歷來重新同步,除非你的CPU非常繁忙地執行其他應用程序。

暫無
暫無

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

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