首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GridBagLayout问题

GridBagLayout问题
EN

Stack Overflow用户
提问于 2016-09-21 16:51:31
回答 1查看 57关注 0票数 0

我正在尝试使用GridBagLayout。我需要一个垂直和水平居中的JLabel -这很简单,我甚至不需要创建任何GridBagConstraints。我还想在右下角放置一个JButton,当我尝试这样做时,我的居中面板正在向左移动,或者按钮正在向上移动。

代码语言:javascript
复制
EXPECTING     GETTING THIS  OR THIS
+-----------+ +-----------+ +-----------+
|           | |           | |           |
|           | |           | |           |
|           | |           | |           |
|   +---+   | | +---+     | | +---+     |
|   |   |   | | |   |     | | |   |     |
|   +---+   | | +---+     | | +---++---+|
|           | |           | |      |   ||
|           | |           | |      +---+|
|       +---+ |       +---+ |           |
|       |   | |       |   | |           |
+-------+---+ +-------+---+ +-----------+

bigPanel = new JPanel();
bigPanel.setPreferredSize(new Dimension(320, 640));
bigPanel.setLayout(new GridBagLayout());

label = new JLabel();
label.setPreferredSize(new Dimension(100,95));

button = new JButton();
button.setPreferredSize(new Dimension(100,25));

GridBagConstraints c = new GridBagConstraints();

c.anchor = GridBagConstraints.CENTER;
bigPanel.add(label, c);

c.anchor = GridBagConstraints.LAST_LINE_END;
bigPanel.add(button, c);

我也在尝试使用这里描述的其他约束,http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html,但每次都会出现错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-21 17:17:22

如果组件不填充单元格,则anchor设置组件在单元格中的位置。

您尚未定义布局的网格。默认行为是从左到右添加组件。

下面是一个使用GridBagLayout实现所需功能的示例。标签和按钮放在同一个单元格中,该单元格填充了面板。

代码语言:javascript
复制
public class Test extends JPanel {
    public Test() {
        super();
        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWeights = new double[] { 1.0 }; // expands the  1rst cell of the layout on the vertical axis
        gridBagLayout.rowWeights = new double[] { 1.0 }; // expands the 1rst cell of the layout on the horizontal axis
        setLayout(gridBagLayout);

        JLabel label = new JLabel("test");          
        label.setOpaque(true);
        label.setBackground(Color.RED);
        label.setPreferredSize(new Dimension(100, 95));
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.gridx = 0; // set label cell (0,0)
        gbc_label.gridy = 0;
        gbc_label.insets = new Insets(0, 0, 5, 5);

        add(label, gbc_label);

        JButton button = new JButton("button");
        GridBagConstraints gbc_button = new GridBagConstraints();
        gbc_button.gridx = 0; // set buttoncell (0,0)
        gbc_button.gridy = 0;
        gbc_button.anchor = GridBagConstraints.SOUTHEAST;

        add(button, gbc_button);
        button.setPreferredSize(new Dimension(100, 25));
    }
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39611764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档