0

I am new to java fx. I am creating a basic GUI which is meant to look like this: enter image description here

However, when I try my image looks like this:

enter image description here

I am unsure as to why there is a large gap between the two buttons. I am using the grid pane format. Here is my code:

public class Main extends Application {
@Override
public void start(Stage stage) {
    //Creating Text field
    TextField textField1 = new TextField();

    //Creating Buttons
    Button submit = new Button("Submit");
    Button cancel = new Button("Cancel");

    //Creating a Grid Pane
    GridPane gridPane = new GridPane();

    //Setting size for the pane
    gridPane.setMinSize(200, 100);

    //Setting the padding
    gridPane.setPadding(new Insets(10, 10, 10, 10));

    //Setting the vertical and horizontal gaps between the columns
    gridPane.setVgap(5);
    gridPane.setHgap(1);

    //Setting the Grid alignment
    gridPane.setAlignment(Pos.CENTER);

    //Arranging all the nodes in the grid
    gridPane.add(textField1, 0, 0);
    gridPane.add(submit, 0, 1);
    gridPane.add(cancel, 1,1);

    //Creating a scene object
    Scene scene = new Scene(gridPane);

    //Setting title to the Stage
    stage.setTitle("Simple Form");

    //Adding scene to the stage
    stage.setScene(scene);

    //Displaying the contents of the stage
    stage.show();
}
public static void main(String args[]){
    launch(args);
}

}

Help would be appreciated :-)

1 Answers1

2

What happens here is that your TextField is set in the top-left corner (0,0), but only spans a single column. You can see that the cancel Button, which is in the bottom right corner (1,1), starts where the TextField stops (if you look only at the x-position).

There is a debug option for GridPanes so you can visualize more what happens. Just call

gridPane.setGridLinesVisible(true):

The solution for this is to set the TextField to obtain/span 2 columns. You can do so by either calling:

GridPane.setColumnSpan(textField1, 2);

Or use a different add method:

gridPane.add(textField1, 0, 0, 2, 1);

See https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/GridPane.html for more information about how the GridPane works.

n247s
  • 1,898
  • 1
  • 12
  • 30