我在Swing中玩GridBagLayout
,我注意到左边的锚点是正确的,但顶部的锚点是-60像素。我知道窗户的确切尺寸,960x640。我正在制作两个列:一个在左侧有两个面板(网格高度为两个面板为2),另一个在右侧有三个面板(网格高度为1,2和1)。这是代码:
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);
我很欣赏代码不干净,它不是它的样子,我只是想确保我能够得到我需要先工作的布局。
结果如下:
因为布局开始将对象放在顶部-60像素处,所以底部有一个60像素的间隙。
有没有人遇到这样的事情?这令我感到困惑。
答案 0 :(得分:2)
我认为这是那个布局经理把它举起来的那个时刻之一,然后说,"嗯,这是我能做的最好的时刻你给我的是什么" 。
如果您将constraints.gridheight = 2;
更改为constraints.gridheight = 3;
infoPanel2
它将会正常工作。
我"想想" 它与第一列的总高度相比,与第一列相比有一些组合(不考虑行跨越)。允许第二行扩展超出两行似乎允许它折叠额外的空间。
它的价值。我可能会把这两列放在单独的面板上,然后将这两个面板放在一起,但那只是我...