1

I want to add a Composite to Eclipse that appears when a certain checkbox is checked. The composite will be comprised of 2 parts: a WARNING_ICON and a label with some text.

I can't seem to get the layout quite right - I want to display the image and label side by side. Here's my section of the code:

        final Composite warningComposite = new Composite(parent, SWT.NONE);
        warningComposite.setLayout(new GridLayout(2, false));
        warningComposite.setLayoutData(new GridData(0, 0, true, false));

        Label l = SWTUtilities.createLabel(composite, "", -1, -1, 1, GridData.BEGINNING);
        final Image img = PlatformUI.getWorkbench().getDisplay().getSystemImage(SWT.ICON_WARNING);
        l.setImage(img);
        l.setLayoutData(new GridData());

        l = SWTUtilities.createLabel(composite, "Wizards Gone Wild", -1, -1, 1, GridData.END);

And the SWTUtilities.createLabel method:

public static Label createLabel(final Composite parent, final String label, final int width, final int indent, final int span, final int style) {
        Assert.isNotNull(parent);
        Assert.isNotNull(label);
        final Label control = new Label(parent, SWT.WRAP);
        control.setText(label);
        if (width > 0 || indent > 0 || span > 0) {
            final GridData data = new GridData(style);
            if (width > 0)
                data.widthHint = width;
            if (indent > 0)
                data.verticalIndent = indent;
            if (span > 1)
                data.horizontalSpan = span;
            control.setLayoutData(data);
        }
        return control;
    }
4

1 回答 1

2

There you go:

public static void main(String[] args)
{
    Display d = new Display();
    final Shell shell = new Shell(d);
    shell.setLayout(new GridLayout(2, false));

    Label image = new Label(shell, SWT.NONE);
    image.setImage(d.getSystemImage(SWT.ICON_WARNING));
    image.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    Label text = new Label(shell, SWT.NONE);
    text.setText("SOME TEXT HERE");
    text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));


    shell.pack();
    shell.open();
    while (!shell.isDisposed())
        while (!d.readAndDispatch())
            d.sleep();
}

Looks like this:

enter image description here


Here is the explanation: SWT does not support vertical alignment of text within the Label (because not all OSs support it). The solution is to align the label at the center of the parent, rather than the text within the label.

于 2013-04-23T16:28:16.840 回答