我想像这样布局我的 JPane:
-------
| |
| |
| |
-------
| |
-------
这样,顶部部分比底部部分更大/更高(顶部部分由另一个 JPanel 组成,并使用 Graphics 对象来显示图像,而底部部分也由另一个 JPanel 组成,但使用 Graphics 对象来绘制一些线条和文字)。
我听说最好的方法是使用 GridBagLayout 和 GridBagConstraints。
我正在尝试找出 GridBagConstraints 的适当属性,但遇到了一些困难。这就是我到目前为止所拥有的......
对于顶部部分,我有:
gridx = 0
gridy = 0
weighty = 1.0; // expand downwards, because the bottom should never expand in the Y direction
fill = GridBagConstraints.BOTH
对于底部部分,我有:
gridx = 0
gridy = 1
fill = GridBagConstraints.HORIZONTAL
anchor = GridBagConstraints.PAGE_END
不幸的是,最终发生的所有事情都是出现一个大的灰色矩形(我的应用程序有白色背景) - 没有图像加载,没有线条/文本出现。
我应该怎么办?我应该调整什么?
我读过一些教程,但它看起来真的很令人困惑,我在我的第一个应用程序中让它工作,但现在当我尝试这样做时,它似乎对我不起作用。
一般来说,对于gridbag布局
这可以按照你的期望工作
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 panel
cst.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 panel
cst.weighty = 0.0;
getContentPane().add(pnlBottom, cst);
此外,如果你想使用 gridbag 布局,我建议你尝试 painless-gridbag 库http://code.google.com/p/painless-gridbag/(我是该库的作者)。它不能为您解决这个问题(因为您的问题涉及在 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)