如何根据较短的文本标签包装较长的文本标签?

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

我在 JFace 对话框中有两个标签。一种是短文,一种是长文。我希望较长的文本在长度超过短文本的长度时换行(不应换行)。

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;
    }
}

我认为您必须计算出第一个标签文本的长度并将其用作第二个标签布局的宽度提示才能执行此操作:

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.");