是否可以将FormLayout 放入GridLayout 中?

Is it possible to put FormLayout into GridLayout?

我正在尝试将 FormLayout 组合放入 GridLayout 网格中,但出现异常。我做错了什么还是不可能?这是我的代码:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class formlayout {
    public static void main(String[] args)
    {
        Display display = new Display();
        Shell shell = new Shell(display);
        GridLayout layout= new GridLayout(1, false);
        shell.setLayout(layout);

        Composite inputs = new Composite(shell, SWT.NONE);
        inputs.setLayout(new FormLayout());
        FormData fd1 = new FormData();
        fd1.left = new FormAttachment(0, 0);
        fd1.right = new FormAttachment(100,0);
        inputs.setLayoutData(fd1);

        Button button1 = new Button(shell, SWT.PUSH);
        button1.setText("B1");
        button1.setLayoutData(new FormData());
        FormData formData = new FormData();
        formData.left = new FormAttachment(20,0);
        formData.right = new FormAttachment(100,0);
        button1.setLayoutData(formData);

        Button button2 = new Button(shell, SWT.PUSH);
        button2.setText("B2");
        button2.setLayoutData(new FormData());
        FormData formData2 = new FormData();
        formData2.left = new FormAttachment(0,0);
        formData2.right = new FormAttachment(20,0);
        button2.setLayoutData(formData2);    

        shell.open();
        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
        display.dispose();
    }
} 

我得到的异常是:

Exception in thread "main" java.lang.ClassCastException: org.eclipse.swt.layout.FormData cannot be cast to org.eclipse.swt.layout.GridData

这当然只是一个演示问题的示例脚本。实际上 shell 在代码中的定义较低,它被设置为 GridLayout 所以我不能真正改变它,但我仍然需要使用 FormLayout 来实现我的按钮目标。

在此代码中:

Composite inputs = new Composite(shell, SWT.NONE);
inputs.setLayout(new FormLayout());
FormData fd1 = new FormData();
fd1.left = new FormAttachment(0, 0);
fd1.right = new FormAttachment(100,0);
inputs.setLayoutData(fd1);

您正在 inputs 的布局数据中设置 FormData。布局数据由为控件的 父级 指定的布局使用 - 在本例中,父级是 shell,它使用 GridLayout

因此,当 shell 的网格布局正在执行布局时,它期望其所有子项在布局数据中都有一个 GridData,但是您有 FormData,所以演员表它正在做失败。

inputs的布局数据指定GridData,只为inputs的子控件使用FormData