GridBag布局,定位件

时间:2016-07-18 17:52:45

标签: java swing layout-manager gridbaglayout

我想要的是左上角的标签和复选框以及右下角的三个按钮。 但是,锚点没有正常工作。

结果: enter image description here

代码:

    JPanel bottomPanel = new JPanel( new GridBagLayout() );

    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(0, 0, 0, 20);
    c.anchor = GridBagConstraints.NORTHEAST;
    bottomPanel.add(spinachLabel, c);

    c = new GridBagConstraints();
    c.gridx = 1;
    c.gridy = 0;
    c.anchor = GridBagConstraints.NORTHEAST;
    bottomPanel.add(checkbox, c);

    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 5;
    c.weightx = 0.5;
    c.insets = new Insets(0, 0, 0, 5);
    c.anchor = GridBagConstraints.SOUTHWEST;
    bottomPanel.add(applyButton, c);

    c = new GridBagConstraints();
    c.gridx = 1;
    c.gridy = 5;
    c.weightx = 0.5;
    c.insets = new Insets(0, 0, 0, 5);
    c.anchor = GridBagConstraints.SOUTHWEST;
    bottomPanel.add(refreshButton, c);

    c = new GridBagConstraints();
    c.gridx = 2;
    c.gridy = 5;
    c.weightx = 0.5;
    c.anchor = GridBagConstraints.SOUTHWEST;
    bottomPanel.add(cancelButton, c);

    return bottomPanel;

1 个答案:

答案 0 :(得分:2)

首先,我们需要澄清GridBagConstraints.anchor的作用:它指定组件在GridBagLayout单元格中的位置。

spinachLabel被放置在gridx = 0处.applyButton也被放置在gridx = 0处。因此,它们被保证放置在同一列中的单元格中。它们各自的锚约束可以在它们的单元格中移动它们的位置,但不能自己移动单元格。

其次,您尚未设置任何weighty约束。每当使用GridBagLayout的容器大于其子组件的首选大小时,它就会使用GridBagLayout的权重约束来决定哪些单元将增长以占用额外的空间。当根本没有权重约束时,就像布局中垂直维度的情况一样,GridBagLayout不会给任何单元格提供额外的空间,而是将它们居中。这就是你所看到的:由于没有单元格设置weighty,所有单元格都是垂直居中的。

总之,除非您设置了一些肯定的weighty约束,否则您的组件将永远不会显示在顶部和底部。

这似乎不能很好地利用GridBagLayout。当您想要在边缘放置组件时,BorderLayout通常是更好的选择:

JCheckBox checkbox = new JCheckBox("Enable Spinach Study");

JButton applyButton = new JBUtton("Apply");
JButton refreshButton = new JBUtton("Refresh");
JButton cancelButton = new JBUtton("Cancel");

JComponent buttonPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
buttonPane.add(applyButton);
buttonPane.add(refreshButton);
buttonPane.add(cancelButton);

JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(checkbox, BorderLayout.PAGE_START);
bottomPanel.add(buttonPane, BorderLayout.PAGE_END);

(JCheckBox应始终包含文本,而不是放在标签的右侧。这样,用户的鼠标目标就会大得多,并且您的用户界面兼容辅助功能。)