How-To's > How can I keep my content in the center of the scene?
Use the code pattern described in this tutorial to keep a Node in the center of the application scene regardless of the scene size and the type of deployment you use.
In the following example, an image is centered on the scene. However, this approach works universally for all the extensions of the Node class, including shapes, text, UI controls, groups, and containers. Use the translateX and translateY instance variables of the Node class to keep the position of the node in sync with the size of the scene as follows:
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Scene;
import javafx.stage.Stage;
def image = Image {url: "{__DIR__}cappuccino.jpg"}
Stage {
var scene: Scene;
title: "Centering"
scene: scene = Scene {
content: ImageView {
translateX: bind (scene.width - image.width) / 2
translateY: bind (scene.height - image.height) / 2
image: image
}
}
}
When run in the standard execution mode, this code produces the application window with the centered image. The following screen captures show the image position when the application window is resized.
This is how the image is centered when the example is run on the mobile phone and touch-phone emulators.
Tips
- If a specific layout is applied in your example, use the
layoutXandlayoutYvariables to set the position of the graphical content instead of thetranslateXandtranslateYvariables. The calculations should look as follows.
Panel {
width: bind panel.scene.width
height: bind panel.scene.height
content: node
onLayout: function() {
node.layoutX = (scene.width - node.layoutBounds.width)/2 - node.layoutBounds.minX;
node.layoutY = (scene.height - node.layoutBounds.height)/2 - node.layoutBounds.minY;
}
}
API Documentation
Related How-To Topics
Examples
Last Updated: January 2010
[Return to How-To's Home]
Do you have comments about this article? We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of repliesyour information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.



