Basically my GUI is like this:
A frame that contains a free designed layout JPanel called mainPanel
Inside mainPanel are two other panels:
A) toolPanel of layout BoxLayout
B) gamePanelof layout GridLayout
These are the significant bits of the code:
public Normalv3() {
initComponents();
importBombs();
}
public void importBombs() {
rows = Minesweeper.rows;
columns = Minesweeper.columns;
total = rows*columns;
bombsIndexes = new ArrayList<Integer>(Minesweeper.totalBombs);
// Creating a new grid layout and putting
// it inside the old layout
gamePanel.setLayout(new java.awt.GridLayout(rows, columns));
////
Random ran = new Random();
int low = 1;
int high = rows*columns;
int ranValue;
for (int i = 0; i< Minesweeper.totalBombs; i++) {
ranValue = ran.nextInt(high - low) + low;
if(bombsIndexes.contains(ranValue)) {
i--;
continue;
}
bombsIndexes.add(ranValue);
}
////
for (int i = 1; i <= total; i++) {
btnMines b = new btnMines(i);
if(bombsIndexes.contains(i)) {
b.isBomb = true;
b.setIcon(new javax.swing.ImageIcon(
getClass().getResource(
"/minesweeper/resources/bomb.png")));
}
b.setPreferredSize(new Dimension(20, 20));
gamePanel.add(b);
}
this.setResizable(false);
this.setTitle("Minesweeper");
this.pack(); // Sizes frame so that all components
// are at their preferred sizes
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.validate(); // Recalculate layout
this.setVisible(true);
}
The problem is when I increase the number of columns, the width of either the gamePanel or mainPanel increases, but the width of the frame does not.
Example:
How do I change the size of the frame to resize itself based on the panel sizes?
Note: btnMines is basically just a JButton with some variables attached to it.
Bonus question: how would I go about making each button into squares? As you can see, I tried making it square by writing b.setPreferredSize(new Dimension(20, 20));
, but each resulting button is still a rectangle!
Also, I know the code is messy. I used to separate that function into separate functions, but now I decided to put it all in one function just to test it out properly.
I tried adding:
this.setResizable(false);
this.setTitle("Minesweeper");
this.pack(); // Sizes frame so that all components
// are at their preferred sizes
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.validate(); // Recalculate layout
this.setVisible(true);
But it didn’t work since the frame didn’t resize!