2

I'm trying to show Date and time continuously on a JLabel. So on the last tutorial I've watched.the speaker said "You must Use this threads whenever necessary because it takes memory in your program".

So I search other alternatives and i find Timer and TimerTask which is the most efficient way to use on the long run of the program?

Orville
  • 518
  • 7
  • 17

1 Answers1

2

A Timer is used to run a task (i.e: TimerTask) on an interval, after a delay, or a combination of the two. In your case, you can use something like this:

   java.util.Timer timer = new java.util.Timer();
    timer.schedule(new TimerTask() {
        public void run() {
//            do task
        }
    }, 0, 1000);  //updates every second

Note that in order to update a Swing component in a thread other than the Swing thread, you'll need to use a SwingWorker (see Swing Concurrency Tutorial), or user a Swing Timer instead. The code below is using a Swing timer to update the label with a new date every second:

javax.swing.Timer timer1 = new javax.swing.Timer(0, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setText(new Date());
        }
    });

    timer1.setRepeats(true);
    timer1.setDelay(1000);

I haven't tested this, so you may need to tweak it a little to work for you.

Ali Cheaito
  • 3,746
  • 3
  • 25
  • 30