Quick Contact


    JavaFX Timer

    JavaFX is known for its flexibility and easiness. There are several classes available in it and Timer is a class that helps in scheduling the tasks that has to be executed later. The creation of a new object of Timer spawns a thread that is new that can execute the program after a mentioned amount of time. This can help the developer to mention if the timer has to be run at a repeated interval or only once. Timer in JavaFx is denoted by the java.util.Timer class. Let us see more about this topic in the following sections.


    Following is the syntax of JavaFX timer.

    Timer timerobj = new Timer();

    How to Create a Timer in JavaFX?

    Similar to Timer class, the TimerTask class has a role in the execution of timer. It is an abstract class that extends the interface Runnable. However, it does not implement the method run. Moreover, a subclass of the class TimerTask can be created that can override the method run during the time when the timer fires within the overridden method run. For putting this all together, a subclass instance can be passed to Timer.schedule. Otherwise, an anonymous class can also be passed to Timer.schedule.


    Now, let us see some sample examples on JavaFX timer.

    Example #1: JavaFX Program to demonstrate the working of a timer with the help of a button


    //import all the relevant classes
    import java.util.Timer;
    import java.util.TimerTask;
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.Alert;
    import javafx.scene.control.Button;
    import javafx.scene.control.Spinner;
    import javafx.scene.layout.HBox;
    import javafx.stage.Stage;
    //main class
    public class TimerProgramSample extends Application
    //set the delay as 0
    int del = 0;
    public void start(Stage st) {
    private void UIinitialisation(Stage st) {
    //create object for horizantal box
    HBoxhb = new HBox(12);
    //set the padding
    hb.setPadding(new Insets(12));
    //create object for timer class
    Timer tm = new java.util.Timer();
    //create object for spinner class
    Spinner sp = new Spinner(1, 62, 5);
    //set the prefernce width
    //create button
    Button b = new Button("Yayyy. . . Timer works. . .");
    //set the action event on clicking the button
    b.setOnAction(event -> {
    del = (int) sp.getValue();
    //schedule the timer
    tm.schedule(new subtimer(), del*1000);
    //get the children of horizontal box
    hb.getChildren().addAll(b, sp);
    //on close event
    st.setOnCloseRequest(event -> {
    //create a scene
    Scenesc = new Scene(hb);
    //set the title
    st.setTitle("Timer Working");
    //set the scene
    //display the result
    //subclass that extends the TimerTask
    private class subtimer extends TimerTask {
    //run method
    public void run() {
    Platform.runLater(() -> {
    //create object for Alert class
    Alert al = new Alert(Alert.AlertType.INFORMATION);
    //set the title
    al.setTitle("Dialog box");
    //set the header text
    al.setHeaderText("Oh oh.. Time elapsed");
    //create a string
    String c;
    //check the condition of delay
    if (del == 1) {
    // display one second is elapsed
    c = "1 sec elapsed";
    } else
    c = String.format("%d sec elapsed",
    //main method
    public static void main(String[] args) {
    //launch the app

    In this program, all the necessary classes have to be imported. Then, set the delay as 0. Once this is completed, call the method UI initialization as it contains the whole functionalities we have to implement. In that method, create an object for the horizontal box. Then set the padding of the horizontal box. Once this is done, the timer class object and spinner class object can be created. After that, set the preferred width and create the button. As we all know, if a button is created, we have to implement the action event of the same. That is, the functionality that has to trigger on clicking the button has to be mentioned. Here, the delay value is retrieved and the timer is scheduled based on the subclass sub timer that extends the TimerTask. That function gets called which contains the overridden run method. After getting out of the subclass, a scene object can be created, followed by setting the title, scene, and displaying the result.

    On executing the code, a dialog box will appear as shown above. As I have selected 5 seconds and clicked the button, a dialog box as shown below appears after every five seconds.

    Example #2: Simple JavaFX Program to demonstrate the working of Timer


    //import all the relevant classes
    import java.util.Timer;
    import java.util.TimerTask;
    //main class
    public class TimerProgramSample {
    //main method
    public static void main(String[] args) {
    //notify that timer starts
    System.out.println("Here, it starts....");
    //create object for timer
    Timer tm = new Timer();
    //schedule the timer
    tm.schedule(new TimerTask(){
    //override run method
    public void run() {
    //print a message notifying about timer
    System.out.println("Timer begins. . . .");
    }, 5000);
    //tIMER that repeats each 20second
    Timer tr = new Timer() ;
    //schedule the repeating timer
    tr.scheduleAtFixedRate(new TimerTask(){
    //override run methid
    public void run(){
    System.out.println("Timer working. . . .");
    }, 0, 2000);

    Apply now for Advanced Java Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.