如何用Java制作倒数计时器

时间:2016-12-07 15:26:07

标签: java timer countdown

我正在开发此应用程序以在用户指定的时间内关闭/重新启动和休眠计算机。我附上了我正在开发的应用程序的图片。用户可以选择小时,分钟或秒来关闭/重启或在用户给定的时间内休眠计算机。我附上了我正在使用的代码示例,但它没有计算时间

public void cal() {
    int seconds = (int) jSpinner1.getValue();
    int minutes = (int) jSpinner2.getValue();
    int hours = (int) jSpinner3.getValue();

    int SECONDS_IN_A_DAY = 24 * 60 * 60;

    Calendar day = Calendar.getInstance();

    day.set(Calendar.SECOND, seconds);
    day.set(Calendar.MINUTE, minutes);
    day.set(Calendar.HOUR_OF_DAY, hours);


    long difference = day.get(seconds + minutes + hours);
    long allSeconds = difference / 1000;

    long days = allSeconds / SECONDS_IN_A_DAY;
    long secondsDay = allSeconds % SECONDS_IN_A_DAY;

    final long secondsinaDay = secondsDay % 60;
    final long minutesinaDay = (secondsDay / 60) % 60;
    final long hoursinaDay = secondsDay / 3600;

    final java.util.Timer timer = new java.util.Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            System.out.printf("%d hours, %d minutes and %d seconds\n", hoursinaDay, minutesinaDay, secondsinaDay);
            jLabel5.setText(String.valueOf(hoursinaDay));
            jLabel6.setText(String.valueOf(minutesinaDay));
            jLabel7.setText(String.valueOf(secondsinaDay));

            //What should be in here if I needed to count down the Timer??????
        }
    }, 1000, 1000);

}

The picture of my Application

1 个答案:

答案 0 :(得分:1)

如果没有正确解释会发生什么,这很难,但至少你应该计算里面任务的时间值。

任务外部的代码只执行一次,它是每秒执行的run()方法内的代码。

否则,即使任务执行,它也总是在标签中放置相同的值。