I have a GridBagLayout 5 lines per 5 columns. I'm trying to span my first object which is a TilePanel on the 3 lines and 5 columns. It' partially working.
I have line 4 and 5 with object. I would expect the first 3 lines would take more space then line 4 and 5. Actually, the space is equally splited onto the Window. What am I doing wrong? See code snippet below and screenshot:
setLayout(new GridBagLayout());
GridBagConstraints grid = new GridBagConstraints();
// Initialize all the UI components
tilePanel = new TilePanel(gameModel);
grid.fill = GridBagConstraints.BOTH;
// Grid 5 lines by 5 columns
grid.weightx = 5;
grid.weighty = 5;
// tilePanel takes 3 lines and 5 columns
grid.gridwidth = 5;
grid.gridheight = 3;
grid.gridx = 0;
grid.gridy = 0;
this.add(tilePanel, grid);
// Forth Line
goal = new JLabel("Goal: " + gameModel.getGameResult());
currentSum = new JLabel("Current sum: 0");
nextButton = new JButton("NEXT");
resetButton = new JButton("RESET");
grid.gridwidth = 1;
grid.gridheight = 1;
// Forth Line: First column
grid.gridy = 4;
grid.gridx = 0;
this.add(nextButton, grid);
// Forth Line: Second column
grid.gridx = 1;
this.add(resetButton, grid);
// Firth Line
grid.gridy = 5;
// Firth Line: First column
grid.gridx = 0;
goal.setBorder(new LineBorder(Color.BLACK, 1));
this.add(goal, grid);
// Firth Line: Second column
grid.gridx = 1;
currentSum.setBorder(new LineBorder(Color.BLACK, 1));
this.add(currentSum, grid);
// Firth Line: Third column
grid.gridx = 2;
this.add(new JLabel("TIME"), grid);
// Firth Line: Fourth column
grid.gridx = 3;
this.add(new JLabel("RESET"), grid);
// Firth Line: Fifth column
grid.gridx = 4;
this.add(new JLabel("LEVEL"), grid);
Screenshot of Window:
weightx and weighty should be float values, with minimum in 0.0 and maximun in 1.0. Value 1.0 means "get as much space as you can", and 0.0 means "you are the last one to get extra space". You give values of 5, and probably the GridBagLayout is making... whatever it makes.
I would try to set the weigthx to 1.0 and weighty=0.6 (60% of the vertical space) when adding tilePanel and weighty=0.2 when adding the rest (20% of vertical space each row).
But I haven't tested it.