Search code examples
javajavafxlayoutgridpane

JavaFX set margins for items in GridPane


I am trying to get some better layout and for that I would like to setMargin for my items inside a GridPane. This is what I tried (only for the first idLabel, idTextField, nameLabel, nameTextField for testing):

private Pane createCenterPane() {   
    centerGridPane = new GridPane();
    
    centerGridPane.add(createIdLabel(), 0, 0);
    centerGridPane.add(createIdTextField(), 2, 0);
    BorderPane.setMargin(idLabel, new Insets(10, 10, 10, 10));
    BorderPane.setMargin(idTextField, new Insets(10, 10, 10, 10));
    
    centerGridPane.add(createNameLabel(), 0, 1);
    centerGridPane.add(createNameTextField(), 2, 1);
    BorderPane.setMargin(nameLabel, new Insets(10, 10, 10, 10));
    BorderPane.setMargin(nameTextField, new Insets(10, 10, 10, 10));
    
    centerGridPane.add(createDescriptionLabel(), 0, 2);
    centerGridPane.add(createDescriptionTextArea(), 2, 2);
    
    centerGridPane.add(createSeverityLabel(), 0, 3);
    centerGridPane.add(createSeverityComboBox(), 2, 3);
    
    centerGridPane.add(createTypeLabel(), 0, 4);
    centerGridPane.add(createTypeComboBox(), 2, 4);
    
    centerGridPane.add(createDependencyLabel(), 0, 5);
    centerGridPane.add(createDependencyListView(), 2, 5);
    
    return centerGridPane;
}

createIdLabel (the other createsX work similar):

private Label createIdLabel() {
    return idLabel = new Label("Id:");
}

But setMargin doesn't do anything:

enter image description here

I would like to have some spacing between the "rows" and also between the label and the item next to it.

I am quite new to this, so if anything is unclear just let me know! happy for every help!


Solution

  • Use:

    • For margins use GridPane.setMargin(node, insets) instead of BorderPane.setMargin(node, insets)
    • For horizontal space between columns use centerGridPane.setHgap(value)
    • For vertical space between lines use centerGridPane.setVgap(value)