Search code examples
javaanimationjavafxjavafx-8

Two Node Fade In and Fade Out every minute


I am trying to animate two panes using fade-in and fade-out animations. It should animate the first-pane and, after a few seconds, it should fade-out and animate second-pane, and so on.

I tried this code:

Thread thread;

@Override
public void run() {
   changingPane();
}

public void changingPane() {
    thread = new Thread() {
        @Override
        public void run() {
            for (;;) {
                if(mainController.getOpenPane()==0)
                {
                    mainController.nextPane();
                }
                else{
                    mainController.prevPane();
                }
            }
        }

    };
    thread.start();
}

Solution

  • Let's say you have two panes,

    private Pane FIRST_PANE = new Pane();
    private Pane SECOND_PANE = new Pane();
    

    And add these methods for fade-in and fade-out the panes,

    Fade-In Method

    private void fadeInPane(Pane pane) {
         FadeTransition fadeIn = new FadeTransition(Duration.millis(2900), pane);
         fadeIn.setFromValue(0);
         fadeIn.setToValue(1);
         fadeIn.setOnFinished(e -> fadeOutPane(pane));
         fadeIn.play();
    }
    

    Fade-out Method

    private void fadeOutPane(Pane pane) {
         FadeTransition fadeOut = new FadeTransition(Duration.millis(1900), pane);
         fadeOut.setFromValue(1);
         fadeOut.setToValue(0);
         fadeOut.play();
    }
    

    Then call those methods as per your logic and need,

    private void animatePane() {
        boolean first_active = true;
    
        Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {            
    
            if(first_active){
                fadeInPane(FIRST_PANE);
                first_active = false;
            }else{
                first_active = true;
                fadeInPane(SECOND_PANE);
            }
        }),
             new KeyFrame(Duration.seconds(30))
        );
        clock.setCycleCount(Animation.INDEFINITE);
        clock.play();
    }