Java 1.7,时钟格式无法正常工作

Sza*_*ázs 0 java integer javafx datetime-format

我尝试了一个非常简单的时钟(它的工作原理).但问题是,我得到的时间可以是:18:7,而不是18:07.我尝试用整数测试校正< 10,但由于某种原因,它说它永远不会运行.你能告诉我为什么它不会比较以及我如何纠正它?顺便说一句,这是代码:)

import javafx.animation.*;
import javafx.event.*;
import javafx.scene.control.Label;
import javafx.util.Duration;
import java.util.Calendar;

public class DigitalClock extends Label {

    static private String addhour;
    static private String addmin;
    static private String addmonth;
    static private String addday;

    // constructor
    public DigitalClock() {
        bindToTime();
    }

    void bindToTime() {
        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0),
                new EventHandler<ActionEvent>() {
                    @SuppressWarnings("unused")
                    @Override
                    public void handle(ActionEvent actionEvent) {
                        Calendar time = Calendar.getInstance();
                        if (Calendar.HOUR_OF_DAY < 10) {
                            addhour = " 0";
                        } else {
                            addhour = " ";
                        }
                        if (Calendar.MINUTE < 10) {
                            addmin = ":0";
                        } else {
                            addmin = ":";
                        }
                        if ((Calendar.MONTH + 1) < 10) {
                            addmonth = ".0";
                        } else {
                            addmonth = ".";
                        }
                        if (Calendar.DAY_OF_MONTH < 10) {
                            addday = ".0";
                        } else {
                            addday = ".";
                        }
                        setText(addhour + time.get(Calendar.HOUR_OF_DAY)
                                + addmin + time.get(Calendar.MINUTE)
                                + "\n" + time.get(Calendar.YEAR)
                                +addmonth + (time.get(Calendar.MONTH) + 1)
                                + addday + time.get(Calendar.DAY_OF_MONTH));
                    } // end of handle
                } // end of EventHandler
                ), // end of new KeyFrame
                new KeyFrame(Duration.seconds(1))); // end of Timeline
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
    } // end of bindToTime
} // end of class DigitalClock
Run Code Online (Sandbox Code Playgroud)

感谢您的时间.

ljg*_*jgw 5

Calendar.MINUTECalendar类中只是一个常量,而不是time对象中的分钟数.

因此,而不是Calendar.MINUTE < 10你应该写time.get(Calendar.MINUTE) < 10.

不过,我同意Scary Wombat:首先尝试使用SimpleDateFormat.