通常,对于网格布袋布局
如果要使用组件比例,则必须为其比例方向赋予一个权重,并且为此方向设置的任何大小(宽度/高度)都将被布局管理器忽略。
如果您不希望组件缩放,则必须定义组件的大小(如果需要,可以在Java文档中深入探讨此主题)。就底部面板而言,至少需要给其一个首选高度。
这可以按您的期望
pnlTop.setBackground(Color.WHITE);pnlBottom.setBackground(Color.BLUE);// Because you don't want the bottom panel scale, you need to give it a height.// Because you want the bottom panel scale x, you can give it any width as the// layout manager will ignore it.pnlBottom.setPreferredSize(new Dimension(1, 20));getContentPane().setLayout(new GridBagLayout());GridBagConstraints cst = new GridBagConstraints();cst.fill = GridBagConstraints.BOTH;cst.gridx = 0;cst.gridy = 0;cst.weightx = 1.0; // --> You miss this for the top panelcst.weighty = 1.0;getContentPane().add(pnlTop, cst);cst = new GridBagConstraints();cst.fill = GridBagConstraints.HORIZONTAL;cst.gridx = 0;cst.gridy = 1;cst.weightx = 1.0; // You miss this for the bottom panelcst.weighty = 0.0;getContentPane().add(pnlBottom, cst);
更进一步,如果您想使用gridbag布局,建议您尝试使用painless-
gridbag库http://pre.google.com/p/painless-
gridbag/(我是该库的作者)。它不能为您解决此问题(因为您的问题涉及在网格袋布局中管理组件的大小),但可以节省大量键入时间,并使代码更易于维护
pnlBottom.setPreferredSize(new Dimension(1, 20));PainlessGridBag gbl = new PainlessGridBag(getContentPane(), false);gbl.row().cell(pnlTop).fillXY();gbl.row().cell(pnlBottom).fillX();gbl.done();



