JavaFX: Padding and Spacing

This entry is part 15 of 55 in the series JavaFX

Padding and Spacing are commonly used in HTML/CSS design to layout the elements in a page.

When it comes to JavaFX, we use padding and spacing just as we were using them in HTML/CSS.

Consider the earlier example where we have the 2 lines below.

vbox.setPadding(new Insets(10)); // Set all sides to 10
vbox.setSpacing(16); // Gap between nodes

When we apply padding and spacing to Vbox, we are actually applying them to all elements in the Vbox.

In the below example, we are applying them to both the title and the list.

The best way for us to see the difference is to modify the values on both of the statements.

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));
        ListView<String> list = new ListView<String>();
        ObservableList<String> items = FXCollections.observableArrayList(
                "Like A Rolling Stone", "Archtung Baby", "Help!", "Smell Like Teen Spirit", "Hotel California");
        return vbox;
    public static void main(String[] args) {



Series Navigation<< JavaFX: Using Label with Graphics
JavaFX: Setting the margin >>

Leave a comment

Leave a Reply