TimerTask vs Timer vs Thread?

前端 未结 1 395
礼貌的吻别
礼貌的吻别 2021-01-23 05:38

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 take

相关标签:
1条回答
  • 2021-01-23 06:08

    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.

    0 讨论(0)
提交回复
热议问题