I'm new in JavaFX, I would like to create a Grid example with some columns and rows. The grid as below: - first row: the first cell (width = 100) occupies 1 column and the second cell (width = 200) occupies 2 column - second row: the first (width = 200) cell occupies 2 column and the second cell (width = 100) occupies 1 column
But I don't know why there is a unexpected cell appears. As below image:
My code as below:
// Label 1
Label lbl1 = new Label("Label1");
lbl1.setPrefWidth(100);
lbl1.setStyle("-fx-border-style: solid; -fx-background-color: #80aaff; -fx-border-width: 0.25");
// Label 2
Label lbl2 = new Label("Label2");
lbl2.setStyle("-fx-border-style: solid; -fx-background-color:#ff80bf; -fx-border-width: 0.25");
lbl2.setPrefWidth(200);
// Label 3
Label lbl3 = new Label("Label3");
lbl3.setPrefWidth(200);
lbl3.setStyle("-fx-border-style: solid; -fx-background-color:#66ff99; -fx-border-width: 0.25");
// Label 4
Label lbl4 = new Label("Label4");
lbl4.setPrefWidth(100);
lbl4.setStyle("-fx-border-style: solid; -fx-background-color: #ffff66; -fx-border-width: 0.25");
GridPane gridPane = new GridPane();
gridPane.setStyle("-fx-border-style: solid");
// column 0, row 0, column span 1, row span 1
gridPane.add(lbl1, 0, 0, 1, 1);
// column 1, row 0, column span 2, row span 1
gridPane.add(lbl2, 1, 0, 2, 1);
// column 0, row 1, column span 1, row span 1
gridPane.add(lbl3, 0, 1, 2, 1);
// column 2, row 1, column span 2, row span 1
gridPane.add(lbl4, 2, 1, 1, 1);
Can anyone point out my problem? Thank you.

The calculation of the prefered width for the
GridPanewith column spans/overlapping columns often doesn't work quite as expected. The "cell" you see is the background of theGridPanenot covered by any child.To avoid the
GridPanefrom becoming too large, set the column widths viaColumnConstraints:This doesn't prevent the empty "space" from reappearing when the window is resized though. To use the same size for all columns regardless of the width of the
GridPaneusepercentWidth: