是否有可能把进入的FormLayout网格布局?(Is it possible to put For

2019-10-22 02:25发布

我试图把一个复合的FormLayout成一个网格布局的网格,但我得到一个异常。 难道我做错了什么或只是不可能? 这里是我的代码:

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是在代码中定义下,它被设置为网格布局,所以我不能去改变,但我仍然需要使用到的FormLayout我acchive带有按钮的目标。

Answer 1:

在这样的代码:

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);

您设置FormData在布局数据inputs 。 布局数据被用于由用于控制的指定的布局-在这种情况下,亲本是shell这是使用GridLayout

所以,当网格布局shell是做什么的期待布局及其所有子有一个GridData在布局数据,但你必须FormData所以它做的转换失败。

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



文章来源: Is it possible to put FormLayout into GridLayout?
标签: java swt