Issue
In the following layout, how can I add right margin for each rectangle. For example, is there any method that allows to add margin?
@Override
public void start(Stage stage) throws Exception {
HBox hBox = new HBox();
Rectangle rect1 = new Rectangle(100, 100, Color.BLACK);
Rectangle rect2 = new Rectangle(100, 100, Color.GREEN);
Rectangle rect3 = new Rectangle(100, 100, Color.YELLOW);
hBox.getChildren().addAll(rect1, rect2, rect3);
Scene scene = new Scene(hBox, 500, 500);
stage.setScene(scene);
stage.show();
}
Solution
As mentioned by @Phil Freihofner, you can set spacing using hBox.setSpacing()
and margin using static method HBox.setMargin()
:
Rectangle rect1 = new Rectangle(100, 100, Color.BLACK);
Rectangle rect2 = new Rectangle(100, 100, Color.GREEN);
Rectangle rect3 = new Rectangle(100, 100, Color.YELLOW);
HBox hBox = new HBox(rect1, rect2, rect3);
// Space between rectangles
hBox.setSpacing(20);
// Margins
HBox.setMargin(rect1, new Insets(30, 0, 30, 30));
HBox.setMargin(rect2, new Insets(30, 0, 30, 0));
HBox.setMargin(rect3, new Insets(30, 30, 30, 0));
Output without setting spacing or margin:
Output setting spacing and margin:
Answered By - Oboe
Answer Checked By - Katrina (JavaFixing Volunteer)