How-To's > How can I keep my content in the center of the scene?

Version: JavaFX 1.3

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.

The centered image in the desktop window

The centered image in the desktop window

This is how the image is centered when the example is run on the mobile phone and touch-phone emulators.

The centered image on the mobile emulator

The centered image on the mobile emulator

Tips

  • If a specific layout is applied in your example, use the layoutX and layoutY variables to set the position of the graphical content instead of the translateX and translateY variables. The calculations should look as follows.
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.Scene;
    import javafx.scene.layout.Panel;
    import javafx.stage.Stage;
    
    
    def image = Image {url: "{__DIR__}example.gif"}
    var node = ImageView {
            image: image
        };
    var scene: Scene;
    
    Stage {
        title: "Centering"
        scene: scene = Scene {
        content:
            Panel {
               width: bind scene.width
               height: bind 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: April 2010
    [Return to How-To's Home]