可以将FormLayout放入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
当然,这只是一个演示问题的示例脚本。实际上,外壳在代码中的定义较低,并且它被设置为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
。布局数据由为控件的父级指定的布局使用-在本例中,父级是使用GridLayout
的shell
。
因此,当shell
的网格布局正在进行布局时,它希望其所有子对象在布局数据中都有GridData
,但您有FormData
,因此它正在执行的强制转换失败。
inputs
的布局数据指定GridData
,inputs
的子控件只使用FormData
。
相关文章