调整Gridbag布局

noo*_*mer 5 java user-interface swing gridbaglayout

我试图在java中使用GRIDBAG布局实现此布局

public static void addComponentsToPane(Container pane) {
        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }

        JLabel label1,label2,label3,result,title;
        JButton calculate_btn;
        JTextField side1,side2,side3;

    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    if (shouldFill) {
    //natural height, maximum width
    c.fill = GridBagConstraints.HORIZONTAL;
    }


        title = new JLabel("Area of Triangle");
    if (shouldWeightX) {
    c.weightx = 0.5;
    }
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 2;
    c.gridy = -1;
    pane.add(title, c);



    label1 = new JLabel("Side 1: ");
    if (shouldWeightX) {
    c.weightx = 0.5;
    }
    c.fill = GridBagConstraints.HORIZONTAL;
         c.ipady = 20;
    c.gridx = 1;
    c.gridy = 1;
    pane.add(label1, c);

        label2 = new JLabel("Side 2: ");
    if (shouldWeightX) {
    c.weightx = 0.5;
    }
    c.fill = GridBagConstraints.HORIZONTAL;
         c.ipady = 20;
    c.gridx = 1;
    c.gridy = 2;
    pane.add(label2, c);


        label3 = new JLabel("Side 3: ");
    if (shouldWeightX) {
    c.weightx = 0.5;
    }
    c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;
    c.gridx = 1;
    c.gridy = 3;
    pane.add(label3, c);

        side1 = new JTextField("   ");
    if (shouldWeightX) {
    c.weightx = 0.5;
    }
    c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;
    c.gridx = 2;
    c.gridy = 1;
    pane.add(side1, c);

        side2 = new JTextField("Side 3: ");
    if (shouldWeightX) {
    c.weightx = 0.5;
    }
    c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;
    c.gridx = 2;
    c.gridy = 2;
    pane.add(side2, c);

        side3 = new JTextField("Side 3: ");
    if (shouldWeightX) {
    c.weightx = 0.5;
    }
    c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;
    c.gridx = 2;
    c.gridy = 3;
    pane.add(side3, c);

    calculate_btn = new JButton("Calculate");
    //c.fill = GridBagConstraints.HORIZONTAL;
    c.ipady = 30;      //make this component tall
    c.weightx = 0.5;
    c.gridwidth = 3;
    c.gridx = 0;
    c.gridy = 5;
    pane.add(calculate_btn, c);

        result = new JLabel("Result displayed here");
    if (shouldWeightX) {
    c.weightx = 0.5;
    }
    c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 20;
    c.gridx = 2;
    c.gridy = 7;
    pane.add(result, c);


    }
Run Code Online (Sandbox Code Playgroud)

所以上面的代码基本上只是将添加到GUI的组件,但我不是很想得到我想要的,这就是我想要实现的

在此输入图像描述

但这是我用上面的代码得到的

在此输入图像描述

因此,当我编译上面是我最终的,也是如果可能我不希望用户调整窗口大小,我猜一些布尔与窗口属性之一..

Gui*_*let 3

问题是您正在设置ipady垂直“拉伸”组件。您可能正在寻找该insets属性:http://docs.oracle.com/javase/7/docs/api/java/awt/GridBagConstraints.html#insets

尝试使用这个:

c.insets = new Insets(10, 0, 10, 0);
Run Code Online (Sandbox Code Playgroud)