【发布时间】: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 秒才能显示在表单上。
我希望标签和面板会在应用程序启动后立即显示。
【问题讨论】:
-
1) 不要使用
while (true)或utils.Timer,而是使用Swing Timer来更新用户界面。 2) 也不要扩展JFrame。您的问题更有可能是因为第一点。但是为了获得更好的帮助,请尽快发布正确的minimal reproducible example -
请参阅:stackoverflow.com/questions/7816585/…,了解使用
Swing Timer的示例。
标签: java swing jframe designer