GridBagLayout元素没有移动

时间:2013-12-13 13:48:51

标签: java swing layout layout-manager gridbaglayout

我正在尝试移动按钮和标签。我希望按钮位于右下角,标签位于它们正上方,但无论我如何更改布局系统,它们都会卡在同一条线上,根本不会移动。如何让他们搬家?

        setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();

        gc.anchor = GridBagConstraints.CENTER;
        gc.weighty = 1;
        gc.gridx = 0;
        gc.gridy = 0;
        gc.ipadx = 5;
        pane.add(explain_lbl, gc);
        gc.ipadx = 1;
        gc.gridy = 1;
        gc.anchor = GridBagConstraints.PAGE_END; //bottom of space
        pane.add(btn_play_normal, gc);
        gc.ipadx = 6;
        gc.gridy = 1;;
        gc.anchor = GridBagConstraints.PAGE_END; //bottom of space

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.ipady = 0;       //reset to default
        gc.weighty = 1.0;   //request any extra vertical space
        gc.anchor = GridBagConstraints.PAGE_END; //bottom of space
        gc.insets = new Insets(10,0,0,0);  //top padding
        gc.gridx = 1;       //aligned with button 2
        gc.gridwidth = 2;   //2 columns wide
        gc.gridy = 2;       //third row
        pane.add(btn_play_ptr, gc);

1 个答案:

答案 0 :(得分:3)

您没有设置pane接受GridBag组件的容器的布局。您需要将布局设置为GridBagLayout才能使布局正常工作。

具体做法是:

setLayout(new GridBagLayout());  // (A)

//  ....

pane.add(btn_play_normal, gc);  // (B)

// ...

pane.add(btn_play_ptr, gc);    // (C)

您正在使用GridBagConstraints,gc,在(B)和(C)中将组件添加到窗格,但您似乎在(A)中设置this容器的布局(无论它是什么) ,但不是pane容器的那个。

解决方案:设置窗格的布局:

pane.setLayout(new GridBagLayout());