Java實現(xiàn)時間動態(tài)顯示方法匯總
本文所述實例可以實現(xiàn)Java在界面上動態(tài)的顯示時間。具體實現(xiàn)方法匯總?cè)缦拢?/p>
1.方法一 用TimerTask:
利用java.util.Timer和java.util.TimerTask來做動態(tài)更新,畢竟每次更新可以看作是計時1秒發(fā)生一次。
代碼如下:
import java.awt.Dimension; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /** * This class is a simple JFrame implementation to explain how to * display time dynamically on the JSwing-based interface. * @author Edison * */ public class TimeFrame extends JFrame { /* * Variables */ private JPanel timePanel; private JLabel timeLabel; private JLabel displayArea; private String DEFAULT_TIME_FORMAT = "HH:mm:ss"; private String time; private int ONE_SECOND = 1000; public TimeFrame() { timePanel = new JPanel(); timeLabel = new JLabel("CurrentTime: "); displayArea = new JLabel(); configTimeArea(); timePanel.add(timeLabel); timePanel.add(displayArea); this.add(timePanel); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(new Dimension(200,70)); this.setLocationRelativeTo(null); } /** * This method creates a timer task to update the time per second */ private void configTimeArea() { Timer tmr = new Timer(); tmr.scheduleAtFixedRate(new JLabelTimerTask(),new Date(), ONE_SECOND); } /** * Timer task to update the time display area * */ protected class JLabelTimerTask extends TimerTask{ SimpleDateFormat dateFormatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT); @Override public void run() { time = dateFormatter.format(Calendar.getInstance().getTime()); displayArea.setText(time); } } public static void main(String arg[]) { TimeFrame timeFrame=new TimeFrame(); timeFrame.setVisible(true); } }
繼承TimerTask來創(chuàng)建一個自定義的task,獲取當(dāng)前時間,更新displayArea.
然后創(chuàng)建一個timer的實例,每1秒執(zhí)行一次timertask。由于用schedule可能會有時間誤差產(chǎn)生,所以直接調(diào)用精度更高的scheduleAtFixedRate的。
2. 方法二:利用線程:
這個就比較簡單了。具體代碼如下:
import java.awt.Dimension; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /** * This class is a simple JFrame implementation to explain how to * display time dynamically on the JSwing-based interface. * @author Edison * */ public class DTimeFrame2 extends JFrame implements Runnable{ private JFrame frame; private JPanel timePanel; private JLabel timeLabel; private JLabel displayArea; private String DEFAULT_TIME_FORMAT = "HH:mm:ss"; private int ONE_SECOND = 1000; public DTimeFrame2() { timePanel = new JPanel(); timeLabel = new JLabel("CurrentTime: "); displayArea = new JLabel(); timePanel.add(timeLabel); timePanel.add(displayArea); this.add(timePanel); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(new Dimension(200,70)); this.setLocationRelativeTo(null); } public void run() { while(true) { SimpleDateFormat dateFormatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT); displayArea.setText(dateFormatter.format( Calendar.getInstance().getTime())); try { Thread.sleep(ONE_SECOND); } catch(Exception e) { displayArea.setText("Error!!!"); } } } public static void main(String arg[]) { DTimeFrame2 df2=new DTimeFrame2(); df2.setVisible(true); Thread thread1=new Thread(df2); thread1.start(); } }
比較:
個人傾向于方法一,因為Timer是可以被多個TimerTask共用,而產(chǎn)生一個線程,會增加多線程的維護(hù)復(fù)雜度。
注意如下代碼:
jFrame.setDefaultCloseOperation(); // 給關(guān)閉按鈕增加特定行為 jFrame.setLocationRelativeTo(null); // 讓Frame一出來就在屏幕中間,而不是左上方。
將上面方法一稍微一修改,就可以顯示多國時間。代碼如下:
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.Timer; import java.util.TimerTask; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /** * A simple world clock * @author Edison * */ public class WorldTimeFrame extends JFrame { /** * */ private static final long serialVersionUID = 4782486524987801209L; private String time; private JPanel timePanel; private TimeZone timeZone; private JComboBox zoneBox; private JLabel displayArea; private int ONE_SECOND = 1000; private String DEFAULT_FORMAT = "EEE d MMM, HH:mm:ss"; public WorldTimeFrame() { zoneBox = new JComboBox(); timePanel = new JPanel(); displayArea = new JLabel(); timeZone = TimeZone.getDefault(); zoneBox.setModel(new DefaultComboBoxModel(TimeZone.getAvailableIDs())); zoneBox.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { updateTimeZone(TimeZone.getTimeZone((String) zoneBox.getSelectedItem())); } }); configTimeArea(); timePanel.add(displayArea); this.setLayout(new BorderLayout()); 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 void configTimeArea() { Timer tmr = new Timer(); tmr.scheduleAtFixedRate(new JLabelTimerTask(),new Date(), ONE_SECOND); } /** * Timer task to update the time display area * */ public class JLabelTimerTask extends TimerTask{ SimpleDateFormat dateFormatter = new SimpleDateFormat(DEFAULT_FORMAT, Locale.ENGLISH); @Override public void run() { dateFormatter.setTimeZone(timeZone); time = dateFormatter.format(Calendar.getInstance().getTime()); displayArea.setText(time); } } /** * Update the timeZone * @param newZone */ public void updateTimeZone(TimeZone newZone) { this.timeZone = newZone; } public static void main(String arg[]) { new WorldTimeFrame(); } }
本來需要在updateTimeZone(TimeZone newZone)中,更新displayArea的。但是考慮到TimerTask執(zhí)行的時間太短,才1秒鐘,以肉眼觀察,基本上是和立刻更新沒區(qū)別。如果TimerTask執(zhí)行時間長的話,這里就要立刻重新用心的時間更新一下displayArea。
補(bǔ)充:
①. pack() 用來自動計算屏幕大??;
②. TimeZone.getAvailableIDs() 用來獲取所有的TimeZone。
相關(guān)文章
Springboot jdbctemplate整合實現(xiàn)步驟解析
這篇文章主要介紹了Springboot jdbctemplate整合實現(xiàn)步驟解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08MyBatis使用<foreach>標(biāo)簽like查詢報錯解決問題
這篇文章主要介紹了MyBatis使用<foreach>標(biāo)簽like查詢報錯解決問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03Spring?Boot讀取配置文件內(nèi)容的3種方式(@Value、Environment和@ConfigurationP
工作中經(jīng)常會有一些參數(shù)需要配置,同時在代碼里面需要用到,所有就需要配置類讀取,然后在使用的時候注入該類進(jìn)行獲取相關(guān)參數(shù),下面這篇文章主要給大家介紹了關(guān)于Spring?Boot讀取配置文件內(nèi)容的3種方式,需要的朋友可以參考下2023-01-01SpringBoot Web詳解靜態(tài)資源規(guī)則與定制化處理
這篇文章主要介紹了SpringBoot web場景的靜態(tài)資源規(guī)則與定制化,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-06-06Java中Integer.valueOf,parsetInt() String.valueOf的區(qū)別和結(jié)果代碼解析
本文通過代碼給大家講解了JAVA中Integer.valueOf, parsetInt() String.valueOf的區(qū)別和結(jié)果,需要的朋友可以參考下2018-05-05Java基礎(chǔ)之多線程方法狀態(tài)和創(chuàng)建方法
Java中可以通過Thread類和Runnable接口來創(chuàng)建多個線程,下面這篇文章主要給大家介紹了關(guān)于Java基礎(chǔ)之多線程方法狀態(tài)和創(chuàng)建方法的相關(guān)資料,需要的朋友可以參考下2021-09-09