JavaFX实时时间和日期

时间:2017-02-22 06:04:17

标签: java javafx javafx-8

我正在构建一个使用JavaFx的应用程序,它具有一个额外的功能,可以在场景的上角显示当前的日期和时间。由于我是JavaFX的新手,我不知道如何实现这个。

我尝试在swing中使用旧代码,但是我遇到了IllegalStateException错误。

这是我的代码。

MainMenuController.java

@FXML private Label time;

private int minute;
private int hour;
private int second;

@FXML
public void initialize() {

    Thread clock = new Thread() {
        public void run() {
            for (;;) {
                DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
                Calendar cal = Calendar.getInstance();

                second = cal.get(Calendar.SECOND);
                minute = cal.get(Calendar.MINUTE);
                hour = cal.get(Calendar.HOUR);
                //System.out.println(hour + ":" + (minute) + ":" + second);
                time.setText(hour + ":" + (minute) + ":" + second);

                try {
                    sleep(1000);
                } catch (InterruptedException ex) {
                     //...
                }
            }
        }
    };
    clock.start();
}

MainMenu.fxml

 <children>
   <Label fx:id="time" textFill="WHITE">
     <font>
       <Font name="Segoe UI Black" size="27.0" />
     </font>
   </Label>
   <Label fx:id="date" textFill="WHITE">
     <font>
       <Font name="Segoe UI Semibold" size="19.0" />
     </font>
   </Label>
 </children>

Main.java

public class Main extends Application {

   public static void main(String[] args) {
       launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception {
       Parent root = FXMLLoader.load(getClass().getResource("view/MainMenu.fxml"));
       primaryStage.setScene(new Scene(root,1366, 768));
       primaryStage.show();
   }
}

正如您所注意到的,我测试了它在控制台中打印实时时间。是的,它有效,但标签仍然是静态的。

3 个答案:

答案 0 :(得分:7)

我认为您需要FX UI线程Platform.runLater(...),但您可以在控制器类中使用Timeline执行此类操作,

@FXML
public void initialize() {

    Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {        
        second = LocalDateTime.now().getSecond();
        minute = LocalDateTime.now().getMinute();
        hour = LocalDateTime.now().getHour();
        time.setText(hour + ":" + (minute) + ":" + second);
    }),
         new KeyFrame(Duration.seconds(1))
    );
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
}

答案 1 :(得分:4)

@Shekhar Rai的答案效果很好,但这是一个简短的版本,效果也很好。

@FXML
Label dateTime;

@Override
public void initialize(URL location, ResourceBundle resources) {
    initClock();
}

private void initClock() {

    Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        dateTime.setText(LocalDateTime.now().format(formatter));
    }), new KeyFrame(Duration.seconds(1)));
    clock.setCycleCount(Animation.INDEFINITE);
    clock.play();
}

主要优点是您不必定义每个变量(秒,分钟,...)

答案 2 :(得分:-1)

我有一个简单的方法可能会对您有所帮助

public function login(Request $request)
{   
$credentials = [
    'email' => $request->email,
    'password' => $request->password
];

if (auth()->attempt($credentials)) {
    $token = auth()->user()->createToken('TutsForWeb')->accessToken;
    return response()->json(['token' => $token], 200);
} else {
    return response()->json(['error' => 'UnAuthorised'], 401);
}
}