【问题标题】:Setting the constraint twice before calling add()在调用 add() 之前设置约束两次
【发布时间】:2019-07-05 02:25:43
【问题描述】:

我正在使用 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) 组件的默认布局是从左到右。您只想在设置变量时更改布局方向。 2)这似乎是一个错误。 “shouldFill”变量什么都不做,因为正如你所指出的那样,它是无论如何设置的
  • 1) 谢谢,我明白你的意思了。 2)同意你!

标签: java swing gridlayoutmanager


【解决方案1】:

我认为第二个布局方向:c.fill = GridBagConstraints.HORIZONTAL; 是错误的,第一个是有条件的,取决于之前设置的值“shouldFill”。所以我不同意这个变量什么都不做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多