SWT:如何让Composite自动填充它的容器

时间:2016-01-26 18:53:39

标签: java layout swt

在下面的代码中,我使用SWT和draw2d。当我运行该程序时,没有任何显示。经过一些调试后我发现它是因为容器的大小都是0.我必须手动输入像

这样的大小
    canvasData.heightHint = 500;
    canvasData.widthHint = 500;

这很好,但是我需要这些容器以适应形式给予它们的空间。有没有办法实现这个目标?任何建议都会有所帮助。

/* (non-Javadoc)
 * @see org.eclipse.ui.forms.editor.FormPage#createFormContent(org.eclipse.ui.forms.IManagedForm)
 */
@Override
protected void createFormContent( IManagedForm managedForm ) 
{
    super.createFormContent(managedForm);

    ScrolledForm form = managedForm.getForm();  

    Composite tabParent = managedForm.getToolkit().createComposite(form.getBody());
    GridData tabParentData = new GridData(SWT.FILL,SWT.FILL,true,true);
    tabParent.setLayoutData(tabParentData);
    tabParent.setLayout(new GridLayout());

    FigureCanvas canvas = new FigureCanvas(tabParent);
    GridData canvasData = new GridData(SWT.FILL,SWT.FILL,true,true);        
    canvas.setLayoutData(canvasData);

    //diagramContents is an IFigure from draw2d. it holds other IFigures, Labels, ect. 
    //Essentially everything being displayed
    canvas.setContents(diagramContents); 

    //This method is what creates everything being displayed (the stuff in diagramContents)
    refreshDisplayFromModel();

    canvas.pack();  
    tabParent.pack();   
}

2 个答案:

答案 0 :(得分:0)

使用

canvas.getViewPort().setContentsTracksWidth( true );
canvas.getViewPort().setContentsTracksHeight( true );

答案 1 :(得分:0)

抛弃GridLayoutGridData并尝试将FillLayout设置为tabParent,如下所示:

form.getBody().setLayout(new FillLayout()); //*

Composite tabParent = managedForm.getToolkit().createComposite(form.getBody());
tabParent.setLayout(new FillLayout());

FigureCanvas canvas = new FigureCanvas(tabParent);
//no layouting
canvas.setContents(diagramContents); 

FillLayout不需要约束对象,只是让它的孩子抓住所有东西。如果您有多个孩子,我建议您查看RowLayout的简单内容,FormLayout查看复杂的内容,并忘记GridLayout

您也可以摆脱pack()电话。

*:由于您提供了tabParent GridData个对象,我认为您的表单有GridLayout。也为你摆脱了这一点。