I'm doing a clone of Minesweeper in Java. Everything was fine, but I wanted to add a counter at the top. And now, some buttons are off the screen. What layouts I have to change to repair it?
Before adding counter: (https://i.sstatic.net/i8gXP.jpg)
After adding "counter" (https://i.sstatic.net/QXJnm.jpg)
And here's my code:
public static JPanel generate() {
i2w = row*row-ilosc_min;
przyc = new Sap[row][row];
JPanel all = new JPanel(); //panel that contains counter and buttons
JPanel licznik = new JPanel(); //Counter
licznik.setBackground(Color.red);
licznik.setPreferredSize(new Dimension(MyFrame.wym-50, 50)); //counter takes 50 px height and full width of frame
all.add(licznik);
JPanel panel = new JPanel(); //Buttons panel
panel.setVisible(true);
panel.setLayout(new GridLayout(row, row));
for(int x = 0; x < row; x++) { //creating buttons
for(int y = 0; y < row; y++) {
Sap sp = new Sap(x, y); //My buttons that extends JButton
przyc[x][y] = sp;
panel.add(sp); //Adding button to panel
}
}
all.add(panel); //All contains counter and buttons
return all; //Returning it
}
When I don't create a counter panel, buttons are like in the second photo.
Sorry for any mistakes, English is not my main language.
first do you know what was the default layout for both of your panel's ?
and the shortest work solution is to make the root panel use BorderLayout
and when adding the counter call on your root panel object
add(BorderLayout.NORTH,theCounterObject);
and for the button's panel call this on the root panel too
add(BorderLayout.CENTER,theButtonsPanel);
this would solve it in shortened version but it's better to learn not a sip or part but all about layout managers as they are very important for swing , here is start A Visual Guide to Layout Managers.
the pack()
method is not necessary but it's a great way to fetch the perfect size it was a good idea from the comment but the problem was about your layout witch was FlowLayout
and it's the default for panel but you should do it after changing the layout .