2017-02-22 1 views
1

現在、JavaFxを使用してアプリケーションのビルドを行っています。これには、シーンの上隅に現在の日時を表示する特別な機能があります。私はJavaFXの初心者なので、この方法を実装する方法はわかりません。JavaFXライブ日時

スイングで古いコードを使用しようとしましたが、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(); 
    } 
} 

あなたが気づくと、私はそれをコンソールでライブタイムを印刷することをテストしました。ええ、それは働いたが、ラベルはまだ静的です。

+0

サイドノートをあなたのコントローラクラスでTimeLineを使用して、このような何かを行うことができます:あなたは、Java SE 8使用している場合(またはそれ以上)可能であれば、新しいDate&Time APIを使用することをお勧めします。 – Puce

答えて

5

は、私はあなたがそのためのFXのUIスレッドPlatform.runLater(...)が必要だと思うが、あなたは、

@FXML 
public void initialize() { 

    Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {    
     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); 
    }), 
     new KeyFrame(Duration.seconds(1)) 
    ); 
    clock.setCycleCount(Animation.INDEFINITE); 
    clock.play(); 
} 
+0

ありがとうございます。ありがとう! –

+0

うん、幸運! –

+1

毎秒更新されるタイムラインは、リアルタイムから何秒も遅れる可能性があることに注意してください。 'AnimationTimer'を使うことはUIレンダリングが許す限り正確です。また、 'Calendar'クラスの代わりに' LocalTime'と 'DateTimeFormatter'を使う方がきれいです。 –

関連する問題