简体   繁体   中英

JButtons in GridLayout get resized from a certain aspect ratio

I am building a Minesweeper clone, and my startNewGame() method works well. In that method, I also change the field size if the difficulty has been changed.

Here is how it looks on easy (9x9):

And here is how it looks on intermediate (16x16).

It also works well if I have 20x20, 30x30, etc. The problem is that if I change the board to 30x16 (expert), it looks like this . It seems like it starts stretching the buttons after a certain aspect ratio for some reason. I set the minefield JPanel's preferred size to [16 * x, 16 * y] (each cell is 16x16).

Why are my buttons stretching and how can I prevent that from happening?

Here is my startNewGame() method (keep in mind that most things are static so their declarations aren't here):

public static void startNewGame()
// Resets and starts a new Game.
{
    timer.stop();
    timerLabel.setText("00:00");
    clicks = 0;

    int newGridLength, newGridHeight, newNumOfMines;
    
    if (difficulties[0].isSelected())
    {
        newGridLength = 9;
        newGridHeight = 9;
        newNumOfMines = 10;
    }
    else if (difficulties[1].isSelected())
    {
        newGridLength = 16;
        newGridHeight = 16;
        newNumOfMines = 40;
    }
    else if (difficulties[2].isSelected())
    {
        newGridLength = 30;
        newGridHeight = 16;
        newNumOfMines = 99;
    }
    else
    {
        newGridLength = 9;
        newGridHeight = 9;
        newNumOfMines = 10;
    }
     
    GRID_LENGTH = newGridLength;
    GRID_HEIGHT = newGridHeight;
    NUM_OF_MINES = newNumOfMines;
 
    remainingMines = NUM_OF_MINES;
    remainingMinesLabel.setText("" + remainingMines);
  
    buttonGrid.clear();
    cellGrid.clear();
  
    frame.remove(gridPane);
    gridPane = new JPanel();
    gridPane.setLayout(new GridLayout(GRID_LENGTH, GRID_HEIGHT));
    initializeGrid(gridPane);
    gridPane.setPreferredSize(new Dimension(CELL_SIZE * GRID_LENGTH, CELL_SIZE * GRID_HEIGHT));
    frame.add(gridPane, BorderLayout.CENTER);
    frame.pack();
}

I read more into other layouts and converted my program to GridBagLayout , and it's working as intended now.

Result: Expert (30x16)

gridPane.setLayout(new GridLayout(GRID_LENGTH, GRID_HEIGHT));

The GridLayout uses

new GridLayout(rows, columns)

as the parameters.

You are passing the parameters in the wrong order.

Note the easiest to create a GridLayout is to only specify a single non-zero value.

So I would use:

gridPane.setLayout(new GridLayout(0, GRID_LENGTH));

This will specify 30 columns.

Now as you add components to the grid it will wrap every 30 components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM