yamaken1343’s blog

技術ブログもどき

JavaFXで時間管理タイマーを作る [タイマー編]

yamaken1343.hatenablog.jp

時間経過に応じてカウントがインクリメントされて表示されるためのコア部分を作成する

コード(抜粋)

private LabT mainTimer = new LabT();
private LabT allTimer = new LabT();
private LabT researchTimer = new LabT();
private LabT restTimer = new LabT();
private LabT otherTimer = new LabT();

@FXML
private Label mainTimerLabel;
//略

private Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), //時間経過をトリガにするのはTimelineクラスを使う
         new EventHandler<ActionEvent>() {
            public void handle(ActionEvent actionEvent) { //ここのブロック内に書いた処理がDuration.seconds()で示した感覚で実行される。今回は1秒
                mainTimer.timeCount(); //一括でタイマーのカウントアップを命令する
                allTimer.timeCount();
                researchTimer.timeCount();
                restTimer.timeCount();
                otherTimer.timeCount();

                mainTimerLabel.setText(mainTimer.formatPrint()); //表示の更新
                allTimerLabel.setText(allTimer.formatPrint());
                childTimerLabel1.setText(researchTimer.formatPrint());
                childTimerLabel2.setText(restTimer.formatPrint());
                childTimerLabel3.setText(otherTimer.formatPrint());
            }
        }
));

public Controller() { //コンストラクタ
        mainTimer.active(); //カウントアップしたいタイマーのみをアクティブにする
        allTimer.active();
        researchTimer.active();

        timeline.setCycleCount(INDEFINITE); //何回繰り返すか指定する。INDEFINITEで制限なし
        timeline.play(); //動作開始
}

解説

  • コンストラクタでカウントアップしたいタイマーのみをアクティブにしLabT.statusをTrueにする、時間経過で周期的な処理を行うtimelineインスタンスを起動する
  • timelineインスタンス内で各タイマーのカウントアップ命令を行う。このとき、LabT.statusがTrueのもののみ実際にカウントアップされる。
  • 指定したラベルにタイマーの値がセットされ、表示される
  • 1秒毎に繰り返される

yamaken1343.hatenablog.jp