简体   繁体   English

J2ME画布上的倒数计时器

[英]Countdown Timer on J2ME Canvas

In my Application, I need the Countdown timer(like a chronometer in Android) which is implemented on Canvas and display the countdown time to the user. 在我的应用程序中,我需要倒数计时器(类似于Android中的计时器),该计时器在Canvas上实现并向用户显示倒数时间。 How can I implement Countdown Timer on Canvas and display the Countdown time to the user? 如何在画布上实现倒数计时器并向用户显示倒数时间?

Its very easy, you simply need to use two classes TimerTask and Timer class. 非常简单,您只需要使用两个类TimerTaskTimer类。 The TimerTask class is a thread which will execute your particular code while Timer is the class which tells TimerTask when to perform the code defined init. TimerTask类是一个线程,它将执行您的特定代码,而Timer是一个类,它告诉TimerTask何时执行定义为init的代码。 Just study the following code, 只需研究以下代码,

import java.util.Timer;
import java.util.TimerTask;

public class TimerDemo
{
    private MyTimerTask mt;
    private Timer timer;

    public TimerDemo()
    {
        mt = new MyTimerTask();     
        timer = new Timer(); 
        timer.schedule(mt, 1000, 1000);
        System.out.println ( "Countdown Begins " ); 
    }

    public static void main ( String args[] )
    {
        TimerDemo td = new TimerDemo();
    }

    private class MyTimerTask extends TimerTask
    {
        int val = 10;
        public void run()
        {
            if ( val > 0 )
            {
                System.out.println ( "Value : " + val-- );
            }
            else
            {
                timer.cancel();
            }
        }
    }
}

/*************************/
/**********OUTPUT*********
Countdown Begins 
Value : 10
Value : 9
Value : 8
Value : 7
Value : 6
Value : 5
Value : 4
Value : 3
Value : 2
Value : 1
*************************/

You need to use java.util.TimerTask or java.util.Timer and implement The Runnable interface to create a thread. 您需要使用java.util.TimerTask或java.util.Timer并实现Runnable接口来创建线程。 Google it and see the documentation. Google并查看说明文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM