Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

JavaFX rectangle width animation

just a question... is it possible to show the change of the width of a rectangle as an animation? The rectangle itself is a statusbar so a scale in both x directions does not do the job.

thx

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One method would be to animate the width modification within a Timeline as opposed to scaling in both directions. You can simulate the direction by modifying the alignment of the Rectangle's parent

Alignment values:

  • Pos.CENTER : Appears as though the change is occurring in both directions
  • Pos.CENTER_LEFT: Appears as though the change is occurring from the right
  • Pos.CENTER_RIGHT: Appears as though the change is occurring from the left

By experimenting with alignments you can choose the one that best fits your current status bar


Visual representation:

Order of alignment: Right | Center | Left

right center left


SSCCE:

public class RectangleWidthAnimation extends Application{
    @Override
    public void start(Stage primaryStage) throws Exception {
        Rectangle statusBar = new Rectangle(300, 100);
        Button animationButton = new Button("Animate width decrease by 25");
        animationButton.setOnAction(event -> {
            System.out.println("Animation start: width = " + statusBar.getWidth());
            KeyValue widthValue = new KeyValue(statusBar.widthProperty(), statusBar.getWidth() - 25);
            KeyFrame frame = new KeyFrame(Duration.seconds(2), widthValue);
            Timeline timeline = new Timeline(frame);
            timeline.play();
            timeline.setOnFinished(finishedEvent -> System.out.println("Animation end: width = " + statusBar.getWidth()));
        });

        VBox container = new VBox(10, statusBar, animationButton);

        //Experiment with these alignments
        container.setAlignment(Pos.CENTER);
        //container.setAlignment(Pos.CENTER_LEFT);
        //container.setAlignment(Pos.CENTER_RIGHT);

        primaryStage.setScene(new Scene(container, 350, 150));
        primaryStage.show();
    }
}


An alternative to the above could be to use transitions, which you can read about here

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...