swt在formLayout中向右添加小部件

时间:2014-11-13 08:52:28

标签: java swt

这是我的代码:

Composite outer = new Composite(parent, SWT.BORDER);
    outer.setBackground(new Color(null, 207, 255, 206)); // Green

    FormLayout formLayout = new FormLayout();
    formLayout.marginHeight = 5;
    formLayout.marginWidth = 5;
    formLayout.spacing = 5;
    outer.setLayout(formLayout);
    //TOP
    Composite Top = new Composite(outer, SWT.BORDER);
    Top.setLayout(new GridLayout());
    Top.setBackground(new Color(null, 232, 223, 255)); // Blue

    FormData fData = new FormData();
    fData.top = new FormAttachment(0);
    fData.left = new FormAttachment(0);
    fData.right = new FormAttachment(100); // Locks on 10% of the view
    fData.bottom = new FormAttachment(20);
    Top.setLayoutData(fData);

    //BOTTOM
    Composite Bottom = new Composite(outer, SWT.BORDER);
    Bottom.setLayout(fillLayout);
    Bottom.setBackground(new Color(null, 255, 235, 223)); // Orange

    fData = new FormData();
    fData.top = new FormAttachment(20);
    fData.left = new FormAttachment(0);
    fData.right = new FormAttachment(100);
    fData.bottom = new FormAttachment(100);
    Bottom.setLayoutData(fData);

我只想在" TOP"的右侧添加小部件,例如标签图像。复合布局。由于我是swt的新手,因此难以将所有标签对齐到右边。我怎么能实现这个目标?

1 个答案:

答案 0 :(得分:1)

如果要在top的右侧放置另一个宽度,首先需要建议top不要占用100%的可用空间,例如只占空间的一半:

FormData formData = new FormData();
formData.right = new FormAttachment( 50 );

或者您可以保留formData.right未指定(即null),以便小部件将使用其首选宽度。

一旦有另一个小部件的空间,你可以正确地附加一个小部件:

Composite right = new Composite( outer, SWT.BORDER );
right.setBackground( display.getSystemColor( SWT.COLOR_YELLOW ) );
FormData rightFormData = new FormData();
rightFormData.top = new FormAttachment( top, 0, SWT.TOP );
rightFormData.left = new FormAttachment( top );
rightFormData.bottom = new FormAttachment( top, 0, SWT.BOTTOM );
right.setLayoutData( rightFormData );

结果如下:

enter image description here

要了解有关SWT中FormLayout和其他布局的更多信息,我建议使用 Understanding Layouts in SWT文章。虽然这篇文章看起来已经过时,但SWT中的布局从那以后没有改变,因此文章的内容仍然有效。

一旦您熟悉FormLayout并寻找一种不那么冗长的方式来指定定位,您可能需要尝试this FormLayout helper