Overview
In this tutorial, we show you how to a space between Buttons in HBox JavaFX.
Adding space between buttons in HBox by add Region()
We add a
Region with
Hgrow set to ALWAYS between the Buttons.
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
Example add a Region between OK Button and Cancel Button
@FXML
private HBox hbxButtons;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
Button btnOk = new Button();
btnOk.setText("OK");
btnOk.setPrefWidth(100);
btnOk.setPrefHeight(30);
hbxButtons.getChildren().add(btnOk);
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
hbxButtons.getChildren().add(spacer);
Button btnCancel = new Button();
btnCancel.setText("Cancel");
btnCancel.setPrefWidth(100);
btnCancel.setPrefHeight(30);
hbxButtons.getChildren().add(btnCancel);
}
Adding space between buttons in HBox by call setSpacing method
Call
setSpacing method of HBox
package com.jackrutorial;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
public class ExampleController implements Initializable {
@FXML
private HBox hbxButtons;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
Button btnOk = new Button();
btnOk.setText("OK");
btnOk.setPrefWidth(100);
btnOk.setPrefHeight(30);
hbxButtons.getChildren().add(btnOk);
Button btnCancel = new Button();
btnCancel.setText("Cancel");
btnCancel.setPrefWidth(100);
btnCancel.setPrefHeight(30);
hbxButtons.getChildren().add(btnCancel);
hbxButtons.setSpacing(20);
}
}
Adding space between buttons in HBox by edit FXML file
Edit FXML file, then add the spacing attribute
spacing="20"
<HBox fx:id="hbxButtons" layoutX="150.0" layoutY="150.0" prefHeight="50.0" prefWidth="300.0" spacing="20" />