【问题标题】:Java, SWT, FormLayout - why does the order in which I add children matter?Java、SWT、FormLayout - 为什么添加子项的顺序很重要?
【发布时间】:2012-08-21 07:08:47
【问题描述】:

我正在为复合容器使用 FormLayout。 当我添加两个孩子 labelclientArea 时,clientArea 取决于标签 - 只有当我先添加标签时才会出现 clientArea。

在容器上调用 layout(),在添加子元素后没有帮助 - clientArea 不显示。

如何将子级添加到 FormLayout 控制的容器中,使其相互独立?

MyLabel label;
Composite clientArea;   

public MyContainer(Composite parent, int style) {
    super(parent,style);

    //choose the container Layout
    FormLayout layout = new FormLayout();
    this.setLayout(layout);


    clientArea = new Composite(this, SWT.NONE);
    FormData formData4ClientArea = new FormData();
    formData4ClientArea.left = new FormAttachment(0,0);
    formData4ClientArea.top = new FormAttachment(0,5);
    formData4ClientArea.right = new FormAttachment(label,-5);
    formData4ClientArea.bottom = new FormAttachment(100,-5);
    //set the Formdata
    clientArea.setLayoutData(formData4ClientArea);
    clientArea.setBackground(getDisplay().getSystemColor(SWT.COLOR_GREEN));     


    //create the label
    label = new MyLabel(this, SWT.NONE);
    FormData formData4Label = new FormData();
    formData4Label.top = new FormAttachment(0,5);
    formData4Label.right = new FormAttachment(100,-5);
    formData4Label.bottom = new FormAttachment(100,-5);
    //set the FormData
    label.setLayoutData(formData4Label);

【问题讨论】:

  • 许多布局,(例如GridLayout 考虑添加顺序,就好像它们是布局约束一样。

标签: java swt form-layout


【解决方案1】:

formData4ClientArea.right = new FormAttachment(label,-5); 此时,labelnull。它没有被实例化。因此,基本上您将 clientArea 附加到任何内容。如果你想让clientArea附加到label,你需要先实例化label,然后再实例化clientArea

但是,另一方面,为什么顺序对你很重要?

【讨论】:

    【解决方案2】:

    事实上,你实例化组件的顺序并不重要。

    您不能做的是在创建对象之前引用它。正如 Plygnome 所说,问题在于当您创建 FormAttachment 时,Labelnull

    在我们的项目中,我们首先创建所有组件,然后创建它们的所有布局数据对象。

    【讨论】:

      猜你喜欢
      • 2015-12-01
      • 2015-10-22
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      相关资源
      最近更新 更多