Dominik
Dominik

Reputation: 31

How to wrap a long text label according to a shorter one?

I got two labels in a JFace Dialog. One with a short text, one with a long text. I would like the longer text wrapped whenever it's length exceeds the length of the short text (which shouldn't be wrapped).

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class TestDialog {

    public static void main(String[] args) {
        Display display = new Display();
        Shell shell = new Shell(display);

        MyTestDialog dialog = new MyTestDialog(shell);
        dialog.open();

        shell.dispose();

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch())
            display.sleep();
        }
        display.dispose();
    }
}

class MyTestDialog extends Dialog {

    public MyTestDialog(Shell parent) {
        super(parent);
    }

    @Override
    protected Control createDialogArea(Composite parent) {
        Composite container = (Composite) super.createDialogArea(parent);
        container.setLayoutData(new GridData(SWT.NONE, SWT.TOP, true, false));

        Label lbl1 = new Label(container, SWT.NONE);
        GridData lbl1griddata = new GridData(SWT.CENTER, SWT.CENTER, false, false);
        lbl1.setLayoutData(lbl1griddata);
        lbl1.setText("This is a short text. Shorter than the other.");

        Label lbl2 = new Label(container, SWT.WRAP);
        lbl2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        lbl2.setText("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.");

        return container;
    }
}

Upvotes: 0

Views: 378

Answers (1)

greg-449
greg-449

Reputation: 111142

I think you will have to work out the length of the first label text and use that as the width hint for the second label layout to do this:

Label lbl1 = new Label(container, SWT.NONE);
GridData lbl1griddata = new GridData(SWT.CENTER, SWT.CENTER, false, false);
lbl1.setLayoutData(lbl1griddata);
lbl1.setText("This is a short text. Shorter than the other.");

GC gc = new GC(lbl1.getDisplay());
int width = gc.textExtent(lbl1.getText()).x;
gc.dispose();

Label lbl2 = new Label(container, SWT.WRAP);
GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false);
data.widthHint = width;
lbl2.setLayoutData(data);
lbl2.setText("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.");

Upvotes: 1

Related Questions