package jp.example;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.*;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.Scene;
import javafx.util.Duration;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
private final StopWatch stopWatch = new StopWatch();
private final Label elapsed_Label = new Label();
@Override
public void start(final Stage primaryStage) {
elapsed_Label.textProperty().bind(stopWatch.timeProperty().asString());
elapsed_Label.setStyle("-fx-font-size: 6em; -fx-text-fill: RED;");
final ToggleButton button = new ToggleButton();
button.textProperty().bind(Bindings.when(button.selectedProperty()).then("Stop").otherwise("Start"));
button.setOnAction(event -> {
final ToggleButton source = (ToggleButton) event.getSource();
if (source.isSelected()) {
stopWatch.play();
} else {
stopWatch.stop();
}
});
final VBox vbox = new VBox(20);
vbox.setAlignment(Pos.CENTER);
vbox.getChildren().addAll(button, elapsed_Label);
final Scene scene = new Scene(vbox, 400, 320);
primaryStage.setTitle("ストップウォッチ");
primaryStage.setScene(scene);
primaryStage.show();
}
}
class StopWatch {
private final Timeline timeline;
private final Duration START_TIME = Duration.ZERO;
private final ReadOnlyObjectWrapper<Duration> elapsed = new ReadOnlyObjectWrapper<>(START_TIME);
StopWatch() {
timeline = new Timeline(new KeyFrame(Duration.millis(10), event -> {
final Duration duration = ((KeyFrame) event.getSource()).getTime();
elapsed.set(elapsed.get().add(duration));
}));
timeline.setCycleCount(Timeline.INDEFINITE);
}
public ReadOnlyObjectWrapper<Duration> timeProperty() {
return elapsed;
}
public void play() {
elapsed.set(START_TIME);
timeline.play();
}
public void stop() {
timeline.stop();
}
}
Last active
September 9, 2018 04:50
-
-
Save umyuu/e7629e956bcd6cc32f906027a9fda9ae to your computer and use it in GitHub Desktop.
JavaFXでStopWatch
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment