CREW
CREW

Reputation: 936

Can a gridpane automatically resize it's objects to fit? Trying to set a max_width and max_height to a grid and have it resize content. JavaFX

I have a simple question. Can a grid automatically resize the objects in it to fit the grid?

I want to set a max_height and max_width on a grid as well as a min-width and min-height and center that grid in my window.

In my grid, I want to add Spacer Square in all spots. Each spacer has a border. So it will look like an actual grid.

If my grid is 4x4, I want there to be 16 big squares.

If my grid is 16x18, I want there to be 288 squares.

Both options should take up an area of a set amount, the 288 square option having squares a lot smaller than the 16 option in order to fit my grid dimensions.

I checked the gridpane documentation, but am confused if there is an option for me. I don't know the difference between padding, margins, setmaxwidth, setmaxheight (tried this, didnt change a thing).

double dimension_x=100; //max_width of actual square/spacer/gridspace
double dimension_y=100; //max_height of actual square/spacer/gridspace

int grid_x=100; //number of rows
int grid_y=100; //number of columns
Rectangle[][] rectangles = new Rectangle[grid_x][grid_y];

GridPane grid = new GridPane();
double grid_max_x=800;
double grid_max_y=600;
grid.setHgap(1);
grid.setVgap(1);
grid.setPadding(new Insets(16)); //not sure what this does. Attempt Fail
grid.setEffect(addEffect(Color.web("#202C2F"), .61, 12));
grid.setMaxHeight(grid_max_y); //does nothing that it APPEARS to me

for (int x=0;x<grid_x;x++)
{
    for(int y=0;y<grid_y;y++)
    {
        Rectangle temp = new Rectangle(dimension_x,dimension_y);
        grid.add(temp,x,y);
    }
}

Upvotes: 3

Views: 4412

Answers (1)

Sergey Grinev
Sergey Grinev

Reputation: 34498

If you want a field of resizable rectangles you don't need a grid. Just put them on Pane and bind to the pane size:

public void start(Stage stage) {
    Pane root = new Pane();

    final int count = 7; //number of rectangles

    NumberBinding minSide = Bindings
            .min(root.heightProperty(), root.widthProperty())
            .divide(count);

    for (int x = 0; x < count; x++) {
        for (int y = 0; y < count; y++) {
            Rectangle rectangle = new Rectangle(0, 0, Color.LIGHTGRAY);

            rectangle.xProperty().bind(minSide.multiply(x));
            rectangle.yProperty().bind(minSide.multiply(y));
            rectangle.heightProperty().bind(minSide.subtract(2));
            rectangle.widthProperty().bind(rectangle.heightProperty());
            root.getChildren().add(rectangle);
        }
    }

    stage.setScene(new Scene(root, 500, 500));
    stage.show();
}

Upvotes: 5

Related Questions