I'm learning Java so I started off by creating a Digital Clock JFrame Form. It all works, but upon load of the application, it takes about 2/3 second to display my border and my label on the background panel.
File: DigitalClock.java
package digitalclock;
import JForms.DigitalClockJForm;
public class DigitalClock {
public static void main(String[] args) {
new DigitalClockJForm().setVisible(true);
}
}
File: 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
The Label and Panel take 2/3 seconds to display on the form.
Then after 2/3 seconds, everything, including border is displayed correctly:
I would have expected the label and panel to display as soon as the application is launched.
There is no need to subclass JFrame, or even JPanel in your case, since you are not overriding any of their methods. Just create a JPanel and add your components to it, then add that JPanel to a new JFrame, pack the frame, and display it.
Create a Swing.Timer with a 1000 millisecond delay, and in the actionPerformed method update the displayed time.
It is probably overkill to create a new GregorianCalendar every time the actionPerformed method is called. Updating the display by one second each time should be sufficient, perhaps with a new Calendar every several minutes to re-synch, unless your CPU is extremely busy executing other applications.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.