How to pause Java.uti.Timer?

I am developing a JavaFX application where I use java.util.Timerto track the user's mouse movement.

Concept: if the mouse does not move for several seconds in the scene, then the buttons will be invisible every time the mouse button is displayed. And whenever the user places the cursor on the button, the timer will stop. And when you exit the button timer, it will start again.

This is the start timer method.

    public static void startTimer(){

    timer = new Timer();
    task = new TimerTask() {

        @Override
        public void run() {

            if(detection>0){
                Util_Class.getUi_obj().getLeftbuttongroup().setVisible(false);
                Util_Class.getUi_obj().getRightbuttongroup().setVisible(false);
            }else{
                detection++;
            }

        }
    };

    timer.schedule(task, 2000, 2000);
    System.out.println("TIMER STARTED");
    //startTimer();
}

This is a timer stop

public static void stopTimer(){

    timer.cancel();
    System.out.println("TIMER STOPED");
}



public void leftbuttonmovehandler(MouseEvent event){


    if(event.getEventType()==MouseEvent.MOUSE_ENTERED){
        System.out.println("MOUSE ENTERED");
        Main.stopTimer();
    }else if(event.getEventType()==MouseEvent.MOUSE_EXITED){
        System.out.println("MOUSE EXITED");
        Main.start();
    }

}

Now my code works fine when the application starts, but when I restart the application, the callback functions start as expected, but the buttons disappear even though the cursor is on the button.

It would be great if someone helped me.

+4
1

A PauseTransition Button .

, MOUSE_MOVE, PauseTransition ; MOUSE_MOVE Button, PauseTransition , Scene,

private PauseTransition timer;

private void startTimer() {
    btn.setVisible(true);
    btn2.setVisible(true);
    timer.playFromStart();
}

private void stopTimer() {
    btn.setVisible(true);
    btn2.setVisible(true);
    timer.stop();
}

private Button btn, btn2;

@Override
public void start(Stage primaryStage) {
    timer = new PauseTransition(Duration.seconds(3));

    btn = new Button("Button 1");
    btn2 = new Button("Button 2");

    timer.setOnFinished(evt -> {
        btn.setVisible(false);
        btn2.setVisible(false);
    });

    EventHandler<MouseEvent> buttonMouseMoveHandler = evt -> {
        evt.consume();
        stopTimer();
    };

    btn.setOnMouseMoved(buttonMouseMoveHandler);
    btn2.setOnMouseMoved(buttonMouseMoveHandler);

    VBox box = new VBox(100, btn, btn2);

    StackPane root = new StackPane(new Group(box));

    Scene scene = new Scene(root, 500, 500);
    scene.setOnMouseMoved(evt -> {
        startTimer();
    });

    startTimer();

    primaryStage.setScene(scene);
    primaryStage.show();
}
+2

Source: https://habr.com/ru/post/1653460/


All Articles