How To Add Columns to Gridpane in JavaFX

837 Views Asked by At

I'm trying to create a Tic-Tac-Toe-like program with a board size that users can select. I can't figure out how to adjust the size of a gridpane in the code. My only lead was using ColumnConstraints and RowContraints, but I have two issues:

  1. When adding a row or column, it won't add multiple rows and columns in a for loop.
  2. I can't figure out how to resize both the grid and the window so that larger version of the grid is usable.

Code for function here:

public void changeGameBoard(ActionEvent event) {
    if (boardNumber > 2) {
        boardNumber = 50;
        sizeLabel.setText("Set at :" + boardNumber);
        ColumnConstraints column1 = new ColumnConstraints();
        RowConstraints row1 = new RowConstraints();
        for (int i = 0; i < boardNumber; i++) {
            column1.setPrefWidth(100);
            row1.setPrefHeight((100));
        }
        gameBoard.getColumnConstraints().add(column1);
        gameBoard.getRowConstraints().add(row1);
        gameBoard.setMinSize(500,500);
    }
}

I've tried playing with padding in SceneBuilder and with setMinSize of my gridpane (the gameBoard object). I can't find any resources to help though. I'm also working with IntelliJ.

1

There are 1 best solutions below

3
M. Rogers On

The question is a little vague out of context, but assuming "gameBoard" is your grid pane, why not set up your grid pane constraints to be a percentage, something like this.

    GridPane gameBoard = new GridPane();
    ColumnConstraints colThird = new ColumnConstraints();
    colThird.setPercentWidth(1/3);
    gameBoard.getColumnConstraints().addAll(colThird,colThird,colThird);
    RowConstraints rowThird = new RowConstraints();
    rowThird.setPercentHeight(1/3);
    gameBoard.getRowConstraints().addAll(rowThird,rowThird,rowThird);