Java implementation time Dynamic display method summary

Source: Internet
Author: User

This article mainly introduces the Java implementation time dynamic display method summary, very practical functions, the need for friends can refer to the next

The example described in this article can realize the dynamic display time of Java on the interface. The specific implementation methods are summarized as follows:

1. Method one with TimerTask:

Use Java.util.Timer and java.util.TimerTask to do dynamic updates, after all, each update can be seen as a 1-second time.
The code is as follows:

Importjava.awt.Dimension;ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;Importjava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask;ImportJavax.swing.JFrame;ImportJavax.swing.JLabel;ImportJavax.swing.JPanel;/*** This class was a simple JFrame implementation to explain what to * display time dynamically on the jswing-based Inter Face. * @authorEdison **/ Public classTimeframeextendsjframe{/** Variables*/ PrivateJPanel Timepanel;PrivateJLabel TimeLabel;PrivateJLabel Displayarea;PrivateString Default_time_format = "HH:mm:ss"; PrivateString time;Private intOne_second = 1000;  Publictimeframe () {Timepanel=NewJPanel (); TimeLabel=NewJLabel ("CurrentTime:"); Displayarea=NewJLabel ();   Configtimearea (); Timepanel.add (TimeLabel); Timepanel.add (Displayarea);  This. Add (Timepanel); This. Setdefaultcloseoperation (exit_on_close); This. SetSize (NewDimension (200,70));  This. Setlocationrelativeto (NULL); }   /*** This method creates a timer task to update the time per second*/ Private voidConfigtimearea () {Timer TMR=NewTimer (); Tmr.scheduleatfixedrate (NewJlabeltimertask (),NewDate (), One_second); }   /*** Timer task to update the time display area **/ protected classJlabeltimertaskextendstimertask{SimpleDateFormat dateformatter=NewSimpleDateFormat (Default_time_format); @Override Public voidrun () { time=Dateformatter.format (Calendar.getinstance (). GetTime ()); Displayarea.settext (time); } }    Public Static voidMain (String arg[]) {timeframe timeframe=Newtimeframe (); Timeframe.setvisible (true); } }/*how to ask Hovertree.com*/

Inherit TimerTask to create a custom task, get the current time, update Displayarea.
Then create an instance of the timer that executes the timertask once every 1 seconds. Since the use of schedule may have a time error, so the direct invocation of higher precision scheduleatfixedrate.

2. Method two: Using Threads:

This is quite simple. The specific code is as follows:

Importjava.awt.Dimension;ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;ImportJavax.swing.JFrame;ImportJavax.swing.JLabel;ImportJavax.swing.JPanel;/*** This class was a simple JFrame implementation to explain what to * display time dynamically on the jswing-based Inter Face. * @authorEdison **/ Public classDTimeFrame2extendsJFrameImplementsrunnable{PrivateJFrame frame;PrivateJPanel Timepanel;PrivateJLabel TimeLabel;PrivateJLabel Displayarea;PrivateString Default_time_format = "HH:mm:ss"; Private intOne_second = 1000;  PublicDTimeFrame2 () {Timepanel=NewJPanel (); TimeLabel=NewJLabel ("CurrentTime:"); Displayarea=NewJLabel (); Timepanel.add (TimeLabel); Timepanel.add (Displayarea);  This. Add (Timepanel); This. Setdefaultcloseoperation (exit_on_close); This. SetSize (NewDimension (200,70));  This. Setlocationrelativeto (NULL); }  Public voidrun () { while(true) {SimpleDateFormat dateformatter=NewSimpleDateFormat (Default_time_format);  Displayarea.settext (Dateformatter.format (Calendar.getinstance (). GetTime ())); Try{thread.sleep (One_second); }  Catch(Exception e) {Displayarea.settext ("Error!!!"); } }  }     Public Static voidMain (String arg[]) {DTimeFrame2 DF2=NewDTimeFrame2 (); Df2.setvisible (true); Thread Thread1=NewThread (DF2); Thread1.start (); } }/*hwq2.com*/

Comparison:

Individuals tend to approach one, because a timer can be shared by multiple timertask, and generating a thread will increase the complexity of multi-threaded maintenance.

Note the following code:

// add specific behavior to the Close button Jframe.setlocationrelativeto (null//  leave frame out in the middle of the screen instead of the top left.) 

You can display the multi-country time by modifying the above method a little. The code is as follows:

Importjava.awt.BorderLayout;Importjava.awt.event.ActionEvent;ImportJava.awt.event.ActionListener;ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;Importjava.util.Date;ImportJava.util.Locale;ImportJava.util.TimeZone;ImportJava.util.Timer;ImportJava.util.TimerTask;ImportJavax.swing.DefaultComboBoxModel;ImportJavax.swing.JComboBox;ImportJavax.swing.JFrame;ImportJavax.swing.JLabel;ImportJavax.swing.JPanel;/*** A simple World Clock *@authorEdison **/ Public classWorldtimeframeextendsjframe{/** *  */ Private Static Final LongSerialversionuid = 4782486524987801209L; PrivateString time;PrivateJPanel Timepanel;PrivateTimeZone TimeZone;PrivateJComboBox Zonebox;PrivateJLabel Displayarea; Private intOne_second = 1000; PrivateString Default_format = "EEE d MMM, HH:mm:ss";  PublicWorldtimeframe () {Zonebox=NewJComboBox (); Timepanel=NewJPanel (); Displayarea=NewJLabel (); TimeZone=Timezone.getdefault (); Zonebox.setmodel (NewDefaultComboBoxModel (Timezone.getavailableids ())); Zonebox.addactionlistener (NewActionListener () {@Override Public voidactionperformed (ActionEvent e) {updatetimezone (Timezone.gettimezone (String) Zonebox.getselecteditem ());   }    });   Configtimearea (); Timepanel.add (Displayarea);  This. setlayout (NewBorderLayout ());  This. Add (Zonebox, Borderlayout.north); This. Add (Timepanel, borderlayout.center); This. Setlocationrelativeto (NULL);  This. Setdefaultcloseoperation (exit_on_close); This. setvisible (true); Pack (); }   /*** This method creates a timer task to update the time per second*/ Private voidConfigtimearea () {Timer TMR=NewTimer (); Tmr.scheduleatfixedrate (NewJlabeltimertask (),NewDate (), One_second); }   /*** Timer task to update the time display area **/  Public classJlabeltimertaskextendstimertask{SimpleDateFormat dateformatter=NewSimpleDateFormat (Default_format, locale.english); @Override Public voidrun () {dateformatter.settimezone (timeZone); time=Dateformatter.format (Calendar.getinstance (). GetTime ()); Displayarea.settext (time); } }   /*** Update the TimeZone *@paramNewzone*/  Public voidUpdatetimezone (TimeZone newzone) { This. TimeZone =Newzone;}  Public Static voidMain (String arg[]) {Newworldtimeframe ();} }/*how to ask Hovertree.com*/

It would have been necessary to update Displayarea in Updatetimezone (TimeZone newzone). However, considering that the TimerTask execution time is too short, only 1 seconds, with the naked eye observation, basically is and immediately update no difference. If the TimerTask execution time is long, it is necessary to immediately re-focus on the time to update the Displayarea.

Add:

①. Pack () is used to automatically calculate the screen size;
②. Timezone.getavailableids () is used to get all the TimeZone.

Recommendation: http://www.cnblogs.com/roucheng/p/3504465.html

Java implementation time Dynamic display method summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.