Macca Blog

My life experiences with code and design

Make a rectangle grow backwards in JavaFX

Posted on by Mark

I came across a small issue when I was developing some home projects that I’ve got going (namely JFXtras) and I wanted to make a rectangle “grow backwards”.

i.e. the rectangle needs to grow upwards, not downwards when increasing the “height” of a rectangle.

Actually, the solution is quite simple, all you need to do is to create a simple Timeline, that will do 2 things:

  1. Increase the height of the rectangle
  2. Decrease the y-position of the rectangle (at the same speed as the increase of the height)

thats it!

Below is a quick code sample that you can cut and paste to see it in action.

package reversi;

import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

def startYPos = 250.0;
def desiredHeight = 200.0;

var rectYPosition = startYPos;
var rectHeight = 100.0;

var rect = Rectangle {
x: 50,
y: bind rectYPosition,
height: bind rectHeight
width: 250,
height: 100
fill: Color.BLACK
}


Timeline {
keyFrames: [
KeyFrame {
time: 0s
values: [rectYPosition => startYPos tween Interpolator.EASEOUT,
rectHeight => 0 tween Interpolator.EASEOUT]
},
KeyFrame{
time: 2s
values: [rectYPosition => startYPos - desiredHeight tween Interpolator.EASEOUT,
rectHeight => desiredHeight tween Interpolator.EASEOUT]
}
]
}.play();

Stage {
title: "Reverse Growing"
width: 350
height: 300
scene: Scene { content: rect }
}

Pretty simple really isn’t it?

If anyone has a cleaner, easier solution to this small, yet relevant problem, I would love to hear it.

Cheers till next time!
Mark

This entry was posted in animation, FX Script, Java, JavaFX, Timeline. Bookmark the permalink.

Leave a Comment

Your email address will not be published. Required fields are marked *


*