About PauseTransition in javafx

江枫思渺然 提交于 2020-06-09 05:19:06

问题


I created a VBox (root) and added some Button in it. When I click the button with text "Click" (button_to_click), ten other button (an button array with ten elements) will change background color into 'red'. I want per button change its backgr color per second. I used PauseTransition to do this but it didn't work. Here are my code

package sample;

import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.scene.control.*;
import javafx.util.Duration;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{

        VBox root = new VBox();

        Button button_to_click = new Button("Click");

        Button[] buttons = new Button[10];

        root.getChildren().add(button_to_click);

        for(int i = 0; i <= 9; i++){
            buttons[i] = new Button(""+i);
            root.getChildren().add(buttons[i]);
        }

        button_to_click.setOnAction(e->{
            for(int i = 0; i <= 9; i++){
                buttons[i].setStyle("-fx-background-color:red");
                PauseTransition pause = new PauseTransition(Duration.seconds(1));
                pause.play();
            }
        });


        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

All button change its background color at the same time, that isn't what I want.


回答1:


You are treating PauseTransition like it’s a Thread.sleep call. But PauseTransition does not work like that.

And even if it were the same, a sleep call would not do what you want. JavaFX, like most user interface toolkits, is single threaded, so a sleep call would hang the application.

The pause transition occurs in a background thread. What you want is to change a button’s color when the pause finishes:

button_to_click.setOnAction(e -> {
    for (int i = 0; i <= 9; i++) {
        Button button = buttons[i];

        PauseTransition pause = new PauseTransition(Duration.seconds(i));
        pause.setOnFinished(
            f -> button.setStyle("-fx-background-color:red"));
        pause.play();
    }
});

Notice that I have changed the PauseTransition’s duration from seconds(1) to seconds(i). This isn’t the most efficient approach, but it requires the fewest changes to your existing code. It will cause each button’s setStyle method to be invoked after i seconds have passed.



来源:https://stackoverflow.com/questions/62200942/about-pausetransition-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!