Make a rectangle grow backwards in JavaFX
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:
- Increase the height of the rectangle
- 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
About Me
Chesung Subba
Author/Writer
Hello, I'm Chesung Subba, a passionate writer who loves sharing ideas, stories, and experiences to inspire, inform, and connect with readers through meaningful content.
Follow Me
Connect with me and be part of my social media community.
Leave a Reply