JavaFX: Setting the margin

To recap, we know that spacing is to set the spacing in pixels between each element and padding allows us to set the distance in pixels between the edges and the element.

If we would like to set a margin to individual element, we can use the setMargin method.

Here I will only set it for the Text title object and you test it out on the list.

package javafxapplication9;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.control.ListView;
import javafx.stage.Stage;
public class JavaFXApplication9 extends Application {
    public void start(Stage stage) {
        BorderPane border = new BorderPane();
        border.setPrefSize(500, 400);
        Scene scene = new Scene(border);
        stage.setTitle("Layout Sample");;
    private VBox addVBox() {
        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10)); // Set all sides to 10
        vbox.setSpacing(16);              // Gap between nodes
        Text title = new Text("Top 5 Rock Albums");
        title.setFont(Font.font("Arial", FontWeight.BOLD, 14));
        vbox.setMargin(title, new Insets(10));
        ListView<String> list = new ListView<String>();
        ObservableList<String> items = FXCollections.observableArrayList(
                "Like A Rolling Stone", "Archtung Baby", "Help!", "Smell Like Teen Spirit", "Hotel California");
    //    vbox.setMargin(list, new Insets(10));
        return vbox;
    public static void main(String[] args) {

Notice the noticeable gap between the title and the list in the screenshot below.


Series Navigation<< JavaFX: Padding and Spacing
JavaFX: Wrapping The Label >>