Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java FX Set Margin

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);
    }

}
like image 940
Dezzo Avatar asked Dec 07 '22 14:12

Dezzo


1 Answers

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>
like image 180
Zephyr Avatar answered Dec 10 '22 03:12

Zephyr