GridBagLayout中的Componenets对齐

时间:2017-08-05 07:15:35

标签: java swing layout-manager gridbaglayout

我正在使用GridBagLayout来对齐组件。实际上,我有两个按钮,我想这样对齐:

所需的布局:

https://i.stack.imgur.com/4yHu4.jpg

但是以下代码会产生以下布局:

导致布局:

https://i.stack.imgur.com/PtCUt.png

我的代码:

    iconAdd = new ImageIcon(getClass().getResource("../images/add.png"));
    add = new JButton(iconAdd);
    add.setPreferredSize(new Dimension(130, 100));
    add.setBorder(new LineBorder(Color.decode("#9b9999"), 1, true));
    add.setCursor(Cursor.getPredefinedCursor(12));
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weightx = 1;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 5, 5, 5);
    pane.add(add, gbc);

    iconSearch = new 
    ImageIcon(getClass().getResource("../images/search.png"));
    search = new JButton(iconSearch);
    search.setCursor(Cursor.getPredefinedCursor(12));
    search.setPreferredSize(new Dimension(130, 100));
    search.setBorder(new LineBorder(Color.decode("#9b9999"), 1, true));
    gbc.gridx++;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 5, 5, 5);
    pane.add(search, gbc);

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;

public class GridBagLayoutDemo extends JFrame{

    GridBagLayoutDemo(){

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWeights = new double[]{1.0, 1.0, 1.0};
        gridBagLayout.columnWidths = new int[]{0,0,300};
        getContentPane().setLayout(gridBagLayout);

        JButton button1 = new JButton("Long Button");
        GridBagConstraints c1 = new GridBagConstraints();
        c1.fill = GridBagConstraints.HORIZONTAL;
        c1.weightx = 0.0;
        c1.gridwidth = 3;
        c1.gridx = 0;
        c1.gridy = 0;
        getContentPane().add(button1, c1);

        JButton button2 = new JButton("Button 2");
        GridBagConstraints c2 = new GridBagConstraints();
        c2.weightx = 0.5;
        c2.gridx = 0;
        c2.gridy = 1;
        getContentPane().add(button2, c2);

        JButton button3 = new JButton("Button 3");
        GridBagConstraints c3 = new GridBagConstraints();
        c3.weightx = 0.5;
        c3.gridx = 1;
        c3.gridy = 1;
        getContentPane().add(button3, c3);

        pack();
        setVisible(true);
    }


    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GridBagLayoutDemo();
            }
        });
    }
}

enter image description here

答案 1 :(得分:1)

gbc.weightx = 1;

您告诉布局为每个组件提供额外的空间。所以基本上每个组件的大小都是框架的一半。

你真的只想为第二个按钮设置约束,所以它占用了所有剩余的空间。

阅读Swing教程中有关如何使用GridBagLayout的部分,该部分解释了如何使用weightx / y约束。

此外,更简单的解决方案是使用FlowLayout。创建一个FlowLayout的面板。将按钮添加到面板。然后将面板添加到框架的BorderLayout.PAGE_START