在调用add()之前设置约束两次

时间:2019-07-05 02:25:43

标签: java swing gridlayoutmanager

我正在使用Oracle形式的教程来学习GridBagLayout。
众所周知,在被1个组件使用后可以再次设置约束。在这里我注意到作者在调用方法add()之前再次设置了约束。

public class GridBagLayoutDemo {
//Here I have no idea why these 3 lines for
    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;
    final static boolean RIGHT_TO_LEFT = false;

    public static void addComponentsToPane(Container pane) {
//1)why not just ignore the above declaration and just type 
//pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); ?

        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }

        JButton button;
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
//same go to here
    if (shouldFill) {
    //natural height, maximum width
    c.fill = GridBagConstraints.HORIZONTAL;
    }
//2)the author set the constraint in above line,then author set it again in below line
    button = new JButton("Button 1");
    if (shouldWeightX) {
    c.weightx = 0.5;
    }
//here it is
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    pane.add(button, c);

有人请回答我两个问题吗?

1 个答案:

答案 0 :(得分:0)

我认为第二个布局方向:/是一个错误,第一个是有条件的,并且取决于先前的设置值“ shouldFill”。因此,我不同意此变量不执行任何操作。