Below is one approach to address your requirement. Having said that, there may be other better approaches, but this can give the idea of how to start with.
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.util.concurrent.TimeUnit;
public class StopClock_Demo extends Application {
private long time;
@Override
public void start(Stage primaryStage) {
Label callDuration = new Label("00:00:00");
Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {
long millis = System.currentTimeMillis() - time;
String txt = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
callDuration.setText(txt);
}), new KeyFrame(Duration.seconds(1)));
clock.setCycleCount(Animation.INDEFINITE);
Button callBtn = new Button("Call");
callBtn.setOnAction(e -> {
if (clock.getStatus() != Animation.Status.RUNNING) {
time = System.currentTimeMillis();
clock.play();
}
});
Button endCallBtn = new Button("End Call");
endCallBtn.setOnAction(e -> {
if (clock.getStatus() == Animation.Status.RUNNING) {
clock.stop();
}
});
Label duration = new Label("Duration");
VBox vBox = new VBox(callBtn, duration, callDuration, endCallBtn);
vBox.setPadding(new Insets(10));
vBox.setSpacing(10);
Scene scene = new Scene(vBox);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…