The most powerful Shapes are QuadraticCurve and CubicCurve. JavaFX constructs these shapes using 2nd and 3rd degree Bezier curves, respectively, which you can read about here (optional).
The shape of a Bezier curve is defined by control points. You need three control points for a QuadraticCurve and four points for a CubicCurve.
Spend some time playing with a 2nd and 3rd degree Bezier curves here.
Let's use the Desmos graph tool to make a PathTransition. First, zoom out until the lower-right quadrant matches the size of your Scene. Then place the control points to get a desired curve shape. Here's what I came up with.
Pass the control points as the constructor parameters to QuadraticCurve or CubicCurve keeping in mind that the y-values are positive going down.
// Create a Node. Could be any kind.
Rectangle rect = new Rectangle(50, 200, 100, 50);
// Create a CubicCurve to use as our path Shape
CubicCurve path = new CubicCurve(25, 200, 300, 30, 400, 200, 150, 170);
// Create the Transition
PathTransition pt = new PathTransition();
pt.setOrientation(OrientationType.ORTHOGONAL_TO_TANGENT);
pt.setDuration(Duration.seconds(2));
pt.setPath(path);
pt.setNode(rect);
Try it. The rectangle follows path we drew using Desmos!
If you also want to draw the curve, remove any paint fill, give it some line coloring and add it to the root node's list of children to draw.
// Create a Node. Could be any kind.
Rectangle rect = new Rectangle(50, 200, 100, 50);
// Create a CubicCurve to use as our path Shape
CubicCurve path = new CubicCurve(25, 200, 300, 30, 400, 200, 150, 170);
// Optional but useful if you want to draw the path
path.setStroke(Color.LIGHTBLUE); // Outline color
path.setStrokeWidth(5); // Outline width 5
path.setFill(null); // Don't fill the interior
// Create the Transition
PathTransition pt = new PathTransition();
pt.setOrientation(OrientationType.ORTHOGONAL_TO_TANGENT);
pt.setDuration(Duration.seconds(2));
pt.setPath(path);
pt.setNode(rect);
...
root.getChildren().add(rect); // Add rect to the display
root.getChildren().add(path); // Add path to the display
Finally, to draw longer paths you can connect multiple Quadratic or Cubic curves. The last control point for one curve becomes the first control point for the next curve. And if you want smooth joints between connected curves, make sure the slope matches at each joint.
JavaFX provides two classes for handling multiple transitions on one Node.
ParallelTransition Runs multiple transitions simultaneously.
For example, you can rotate while translating.
SequentialTransition Runs multiple transitions one after the other, like a play list.
Last modified: March 13, 2023
Back to Pathtransition