How can I animate the height property of a rectangle object?

时间:2016-10-20 19:34:46

标签: javafx

What I want is really simple but yet couldnt find any solution. Im new with JavaFX and Im getting used with animations. What I want to do is to animate a container with water, the water has to be filled up to the top and then get down again and so on. This is what I did (this is just the "water", I didnt programm the container yet, I wanted first to get the animation right)

public class FormTest extends Application {

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

@Override
public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("The container test");
    primaryStage.setHeight(600);
    primaryStage.setWidth(600);
    Pane pane = new Pane();
    Rectangle rect = new Rectangle(207,327,192,42);
    rect.setFill(Color.CYAN);
    Timeline tl = new Timeline();
    tl.setCycleCount(Timeline.INDEFINITE);
    tl.setAutoReverse(true);

    KeyValue k1 = new KeyValue(rect.heightProperty(),300);
    KeyFrame kf1 = new KeyFrame(Duration.millis(1000),k1);
    tl.getKeyFrames().add(kf1);
    tl.play();
    pane.getChildren().addAll(rect);
    primaryStage.setScene(new Scene(pane));
    primaryStage.show();

}}

The problem is that the "water" animates in the opposite direction (down), timeline is the only way I could manage to understand so far for this kind of animation I want to achieve. How do I get the "water" to go up instead of down? Thanks in advance

2 个答案:

答案 0 :(得分:1)

You want the bottom of the rectangle to stay fixed: initially it is at 327+42=369. So you need to change y so that it is always y+height=369 as height changes, i.e. you want y=-height+369:

rect.yProperty().bind(rect.heightProperty().multiply(-1).add(369));

答案 1 :(得分:1)

Since you want to move the top, not the bottom, but the origin of the Rectangle is the top left, you also need to animate the y property to decrease when the height increases:

KeyValue k1 = new KeyValue(rect.heightProperty(), 300);
KeyValue kv = new KeyValue(rect.yProperty(), rect.getY()-300+rect.getHeight());
KeyFrame kf1 = new KeyFrame(Duration.millis(1000), k1, kv);