I'm playing around with GridBagLayout
in Swing and I noticed the anchor point on the left is correct, but the one at the top is at -60 pixels. I know the exact size of the window, 960x640. I'm making two columns: one with two panels on the left (grid heights are 2 for both) and another with three panels on the right (grid heights are 1, 2 and 1). This is the code:
gameFrame.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.NORTHWEST;
InfoPanel infoPanel = new InfoPanel();
infoPanel.setPreferredSize(new Dimension(320, 320));
infoPanel.setMinimumSize(new Dimension(320, 320));
infoPanel.setMaximumSize(new Dimension(320, 320));
infoPanel.setBackground(Color.BLUE);
constraints.gridx = 0;
constraints.gridy = 0;
//constraints.gridwidth = 1;
constraints.gridheight = 2;
gameFrame.add(infoPanel, constraints);
InfoPanel infoPanel2 = new InfoPanel();
infoPanel2.setPreferredSize(new Dimension(320, 320));
infoPanel2.setMinimumSize(new Dimension(320, 320));
infoPanel2.setMaximumSize(new Dimension(320, 320));
infoPanel2.setBackground(Color.RED);
constraints.gridx = 0;
constraints.gridy = 2;
//constraints.gridwidth = 1;
constraints.gridheight = 2;
gameFrame.add(infoPanel2, constraints);
InfoPanel infoPanel3 = new InfoPanel();
infoPanel3.setPreferredSize(new Dimension(640, 200));
infoPanel3.setMinimumSize(new Dimension(640, 200));
infoPanel3.setMaximumSize(new Dimension(640, 200));
infoPanel3.setBackground(Color.GREEN);
constraints.gridx = 1;
constraints.gridy = 0;
//constraints.gridwidth = 1;
constraints.gridheight = 1;
gameFrame.add(infoPanel3, constraints);
InfoPanel infoPanel4 = new InfoPanel();
infoPanel4.setPreferredSize(new Dimension(640, 240));
infoPanel4.setMinimumSize(new Dimension(640, 240));
infoPanel4.setMaximumSize(new Dimension(640, 240));
infoPanel4.setBackground(Color.YELLOW);
constraints.gridx = 1;
constraints.gridy = 1;
//constraints.gridwidth = 1;
constraints.gridheight = 2;
gameFrame.add(infoPanel4, constraints);
InfoPanel infoPanel5 = new InfoPanel();
infoPanel5.setPreferredSize(new Dimension(640, 200));
infoPanel5.setMinimumSize(new Dimension(640, 200));
infoPanel5.setMaximumSize(new Dimension(640, 200));
infoPanel5.setBackground(Color.PINK);
constraints.gridx = 1;
constraints.gridy = 3;
//constraints.gridwidth = 1;
//constraints.gridheight = 1;
gameFrame.add(infoPanel5, constraints);
gameFrame.pack();
gameFrame.setLocationRelativeTo(null);
I appreciate that the code isn't clean, it's not what it will look like, I just wanted to make sure I can get the layout I need working first.
Here is the result:
Because the layout starts placing objects at -60 pixels off the top, there's a 60 pixel gap at the bottom.
Has anyone come across something like this? It baffles me.