我正在尝试将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来实现我的目标按钮。
答案 0 :(得分:3)
在此代码中:
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
。