×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Markus Oberhauser
Added: Sep 3, 2014 3:28 PM
Views: 20
To show actual time in SWING GUI a seperate thread is needed to update a JLabel text with actual local time. A "normal" Swing-timer runs with delay and on higher cpu load the timer is not accurate enough. To solve this you need the Timer from java.util.Timer package, because it operates with a fixed rate from call to call.
  1. JLabel date = new JLabel();
  2. final Timer clockTimer = new Timer (true);
  3.        
  4.         clockTimer.scheduleAtFixedRate(new TimerTask() {
  5.             @Override
  6.             public void run() {
  7.                 synchronized(date.getTreeLock()) {
  8.                 date.setText(String.format("%tT", new Date()));
  9.             }
  10.           }
  11.         }, 0, 100);