Question

I want to display the date and its name along with running time on Swt label. Here is my code:-

    Label DateLbl = new Label(shell, SWT.NONE);   
    DateLbl.setBounds(0,0,100,50);

    DateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy  HH:mm:ss");
    Calendar cal1 = Calendar.getInstance();


    DateFormatSymbols dfs1 = new DateFormatSymbols();
    String weekdays1[] = dfs1.getWeekdays();

    int day1 = cal1.get(Calendar.DAY_OF_WEEK);

    String nameOfDay1 = weekdays1[day1];


    DateLbl.setText(" "+dateFormat1.format(cal1.getTime()) +             " \n" +"        "+nameOfDay1);

It displays the time, date and date name but i want running second, minute and hour ( a complete virtual clock on Label).

here is o/p for above code - 26/03/2014 12:57:01 wednesday

Time gets updated each time when i launch my application.

Could anyone suggest something to make second, minute, hour run on SWT label.

Was it helpful?

Solution

You can use the java.util.Timer class to run code periodically:

Timer timer = new Timer("clock timer", true);

timer.schedule(new UpdateTimerTask(), 1000l, 1000l);  // Run once a second


private class UpdateTimerTask extends TimerTask
{
  @Override
  public void run()
  {
    // Timer task runs in a background thread, 
    // so use Display.asyncExec to run SWT code in UI thread

    Display.getDefault().asyncExec(new Runnable() 
     {
       @Override
       public void run()
       {
         // TODO update the label
       }
     });  
  }
}

OTHER TIPS

Your question is not clear? Do you want a clock updating with the current time second-by-second?

If so, you need to spawn a thread to sleep and wake every second. The thread then updates the user interface in whatever thread-safe manner is appropriate to swt, and returns to sleep.

For the sleeping thread, you can use either a Timer or a ScheduledExecutorService. Each has its merits.

To update the user-interface… I don't know swt, but expect you need to find the equivalent of SwingWorker used in Swing.

SWT has default native timer support. use below method

org.eclipse.swt.widgets.Display.timerExec(int, Runnable)

please read documentation for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top