Java FX Set Margin
Asked Answered
W

1

11

This simple example creates an area with 2 rectangle areas marked in red. I want to push the right area by n pixels towards the right using the VBox margin method but nothing happens. Why is margin not working in this example ? It works in scene builder though..

public class LayoutContainerTest extends Application {

    @Override
    public void start(Stage primaryStage) {

        VBox areaLeft = new VBox();
        areaLeft.setStyle("-fx-background-color: red;");
        areaLeft.setPrefSize(100, 200);

        VBox areaMiddle = new VBox();
        areaMiddle.setStyle("-fx-background-color: red;");
        areaMiddle.setPrefSize(100, 200);

        VBox areaRight = new VBox();
        areaRight.setStyle("-fx-background-color: red;");
        areaRight.setPrefSize(100, 200);

        VBox.setMargin(areaRight, new Insets(0,0,0,50));

        HBox root = new HBox(areaLeft,areaMiddle,areaRight);
        root.setSpacing(30);



        Scene scene = new Scene(root, 600, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}
Whip answered 28/7, 2018 at 19:11 Comment(0)
H
21

You are using VBox.setMargin() but should be using the HBox method instead:

HBox.setMargin(areaRight, new Insets(0, 0, 0, 50));

The reason being, you are setting the margins for the children of a VBox, while areaRight is the child of a HBox. If you were to use your code and then place areaRight into a VBox, you would be seeing the margin as expected.

You mention that it works in SceneBuilder, but if you inspect the actual FXML code, you'll see that SceneBuilder is correctly using HBox:

<VBox fx:id="areaRight" prefHeight="200.0" prefWidth="100.0" style="-fx-background-color: red;">
     <HBox.margin>
        <Insets left="50.0" />
     </HBox.margin>
  </VBox>
Hornback answered 28/7, 2018 at 19:17 Comment(1)
Wow, that was fast ! Big Thanks. Perfectly clear now.Whip

© 2022 - 2024 — McMap. All rights reserved.