可以将FormLayout放入GridLayout中吗?

Is it possible to put FormLayout into GridLayout?(可以将FormLayout放入GridLayout中吗?)

本文介绍了可以将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。布局数据由为控件的父级指定的布局使用-在本例中,父级是使用GridLayoutshell

因此,当shell的网格布局正在进行布局时,它希望其所有子对象在布局数据中都有GridData,但您有FormData,因此它正在执行的强制转换失败。

inputs的布局数据指定GridDatainputs的子控件只使用FormData

这篇关于可以将FormLayout放入GridLayout中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:可以将FormLayout放入GridLayout中吗?

基础教程推荐