Search code examples
javajavafxposition

Binding label to bottom-center of scene - JavaFX


I am trying to figure out how to center and bind a label perfectly at the bottom of a scene. I have a simple test application here to show what I am working with and what my issue is.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class LabelTest extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Pane root = new Pane();
        Scene scene = new Scene(root, 400, 400);

        Label label = new Label("Testing testing 1 2 3");

        label.layoutXProperty().bind(scene.widthProperty().divide(2).subtract(label.getWidth() / 2));   //Should align label to horizontal center, but it is off  
        label.layoutYProperty().bind(scene.heightProperty().subtract(label.getHeight() + 35));          //Aligns the label to bottom of scene

        root.getChildren().add(label);
        stage.setScene(scene);
        stage.show();
    }
}

The logic behind my positioning makes sense to me, so I am not sure why it is not horizontally centered. I have included a screenshot below to show what the output looks like:

enter image description here

And below is more of what I am wanting it to look like (still off by a bit, but you get the point)

enter image description here

Thanks in advance to anyone who helps me out!


Solution

  • Let layout managers do the layout for you:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    public class LabelTest extends Application {
    
        @Override
        public void start(Stage stage) throws Exception {
    
            Label label = new Label("Testing testing 1 2 3");
            BorderPane root = new BorderPane();
            //center label by
            //BorderPane.setAlignment(label, Pos.CENTER);
            //root.setBottom(label);
            //OR
            root.setBottom(new StackPane(label));
            Scene scene = new Scene(root, 400, 400);
            stage.setScene(scene);
            stage.show();
        }
        public static void main(String[] args) {
            launch(args);
        }
    }