我正在尝试使用 GridBagLayout 布局管理器来实现这一点:
但是,我目前得到的是:
问题是橙色和棕色/灰色面板应该占据第二列,但在运行代码时似乎只想占据第三列。
我用于布局的代码:
Container contentPane = form.getContentPane();
contentPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JPanel pnlGame = new JPanel();
pnlGame.setBackground(Color.green); //temp
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 2;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.85;
c.weighty = 0.65;
contentPane.add(pnlGame, c);
JPanel pnlBuy = new JPanel();
c.gridx = 2;
pnlBuy.setBackground(Color.blue); //temp
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.15;
c.weighty = 0.46;
contentPane.add(pnlBuy, c);
JPanel pnlUpgrade = new JPanel();
pnlUpgrade.setBackground(Color.yellow); //temp
c.gridx = 2;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.15;
c.weighty = 0.19;
contentPane.add(pnlUpgrade, c);
JPanel pnlStats = new JPanel();
pnlStats.setBackground(Color.red); //temp
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 2;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.61;
c.weighty = 0.35;
contentPane.add(pnlStats, c);
JPanel pnlSpeed = new JPanel();
pnlSpeed.setBackground(Color.orange); //temp
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 2;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.38;
c.weighty = 0.04;
contentPane.add(pnlSpeed, c);
JPanel pnlRounds = new JPanel();
pnlRounds.setBackground(Color.gray); //temp
c.gridx = 2;
c.gridy = 3;
c.gridwidth = 2;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.38;
c.weighty = 0.31;
contentPane.add(pnlRounds, c);
那么,我做错了什么?对不起,如果我的英语有点糟糕,和/或我犯的错误非常明显......现在是早上 20 点到 5 点,我度过了漫长的一天。应该很快就到干草了。
更新:
看来,如果我更改棕色/灰色面板的网格宽度,一切似乎都正确对齐,但最终我的布局中出现了令人讨厌的间隙。这里:
i.imgur.com/6JUx2.png
以及面板的代码(包括 Kevin S 建议的修改):
JPanel pnlRounds = new JPanel();
pnlRounds.setBackground(Color.gray); //temp
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.38;
c.weighty = 0.31;
contentPane.add(pnlRounds, c);
那么,有什么我做错了,或者这只是我将不得不忍受的 GridBagLayout 的一些奇怪行为?
不幸的是,由于我的编辑,我丢失了 Bala R 放入的所有嵌入。所以,恐怕我们又回到了图片链接。而且现在好像不能发两个以上的超链接,所以最后一个链接已经被杀掉了,需要复制粘贴进去。
谢谢,山姆