Java implements a time dynamic display method summary

  • 2020-04-01 03:27:24
  • OfStack

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 1: use TimerTask:

Make use of java.util.timer and java.util.timertask to do dynamic updates, after all, each update can be regarded as a one-second Timer.
The code is as follows:


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;

public class TimeFrame extends JFrame
{
 
 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);
 }
 
 
 private void configTimeArea() {
 Timer tmr = new Timer();
 tmr.scheduleAtFixedRate(new JLabelTimerTask(),new Date(), ONE_SECOND);
 }
 
 
 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); 
 } 
}
 


Inherit the TimerTask to create a custom task, get the current time, and update the displayArea.
Then create an instance of a timer and execute the timertask every 1 second. Since there may be a time error with schedule, the more accurate scheduleAtFixedRate is called directly.
 
2. Method 2: using threads:

This is a little bit easier. The specific code is as follows:


import java.awt.Dimension;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

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(); 
 } 
}

Comparison:

I prefer method 1, because Timer can be Shared by multiple timertasks, and the generation of one thread will increase the maintenance complexity of multiple threads.

Note the following code:


jFrame.setDefaultCloseOperation(); //Add specific behavior to the close button
jFrame.setLocationRelativeTo(null); //Let the Frame come out in the middle of the screen, not in the top left.

A slight modification of the above method shows the multinational time. The code is as follows:


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;

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();
 }
 
 
 private void configTimeArea() {
 Timer tmr = new Timer();
 tmr.scheduleAtFixedRate(new JLabelTimerTask(),new Date(), ONE_SECOND);
 }
 
 
 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);
 }
 }
 
 
 public void updateTimeZone(TimeZone newZone)
 {
 this.timeZone = newZone;
 }
 
 public static void main(String arg[])
 {
 new WorldTimeFrame();
 } 
}

You should have updated the displayArea in the updateTimeZone(TimeZone newZone). However, considering the TimerTask's short execution time, which is only 1 second, when viewed with the naked eye, it is basically the same as an immediate update. If the TimerTask takes a long time to execute, the displayArea should be updated immediately.

Supplement:

Pack () is used to automatically calculate the screen size;
GetAvailableIDs () is used to get all the timezones.


Related articles: