Search code examples
javajavafxgridpane

JavaFX - Inflating a GridPane to parent's size


I am trying to create a GUI for one of my programs. This is my first time using JavaFX.

For starters, I would like to have a GridPane that takes up the entire window.

I have tried everything I could find: setMinWidth/Height, setPrefSize, minWidth, etc. Nothing worked.

Following is the part of the code that defines the GridPane, with two Text objects:

    //Grid layout
    GridPane grid = new GridPane();
    grid.setPrefSize(STAGE_WIDTH, STAGE_HEIGHT);
    grid.setMaxSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
    grid.setMinSize(STAGE_WIDTH, STAGE_HEIGHT);

    //grid.minWidth(STAGE_WIDTH);
    //grid.minHeight(STAGE_HEIGHT);

    grid.setGridLinesVisible(true);
    grid.setAlignment(Pos.CENTER);
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));

    //Text
    final Text count = new Text("Count");
    grid.add(count,0,0);

    final Text total = new Text("Total");
    grid.add(total,1,0);

    Scene scene = new Scene(grid, STAGE_WIDTH, STAGE_HEIGHT);
    primaryStage.setScene(scene);
    primaryStage.show();

Does anybody know how to successfully program this simple attribute? A GridPane that takes up the entire window? What am I missing?

Thank you LD


Solution

  • Delete all these

    grid.setPrefSize(STAGE_WIDTH, STAGE_HEIGHT);
    grid.setMaxSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
    grid.setMinSize(STAGE_WIDTH, STAGE_HEIGHT);
    grid.minWidth(STAGE_WIDTH);
    grid.minHeight(STAGE_HEIGHT);
    

    and use ColumnConstraints with optionally RowConstraints:

    ColumnConstraints cc = new ColumnConstraints(100, 100, Double.MAX_VALUE, 
                                         Priority.ALWAYS, HPos.CENTER, true);
    grid.getColumnConstraints().addAll(cc, cc);
    
    RowConstraints rc = new RowConstraints(20, 20, Double.MAX_VALUE, 
                                         Priority.ALWAYS, VPos.CENTER, true);
    grid.getRowConstraints().addAll(rc, rc);
    

    You will get more control on each cell in this way, by adding individual column and row constraints for it. Please refer to javadocs for more detailed explanations.