Reputation: 103
I would like to achieve the following using JavaFX-8:
The idea is to simulate a duration of a phone call from pressing "Call" to pressing "End Call".
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Button callBtn = new Button("Call");
Button endCallBtn = new Button("End Call");
Label duration = new Label("Duration");
Label callDuration = new Label("00:00:00");
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);
}
}
Upvotes: 0
Views: 166
Reputation: 9959
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);
}
}
Upvotes: 1