gpt4 book ai didi

java - 如何使用GridBagConstraints创建布局?

转载 作者:行者123 更新时间:2023-12-02 00:49:27 25 4
gpt4 key购买 nike

我想像这样布局我的 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布局

  • 如果您想要组件缩放,则必须为其缩放方向指定权重,并且您为该方向设置的任何尺寸(宽度/高度)都将被布局管理器忽略。

  • 如果您不想要组件比例,则必须定义组件的大小(如果需要,您可以在 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 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();

关于java - 如何使用GridBagConstraints创建布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9014068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com