Search code examples
eclipseeclipse-pluginswte4

Why composite is expanded by text field?


I created a text field which used GridLayout and I set the 3rd parameter of the GridData (grabExcessHorizontalSpace) to true. The Text field is not getting wrap into multiple line when I set a very long sequence of non-whitespace characters won't be split into lines. The Composite is expanded by text filed.

Below is my code:

Composite composite = new Composite(m_shell, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
composite.setLayout(new GridLayout(2, false));

Label label = new Label(composite, SWT.LEAD);
label.setText("Label");
label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));

Text text = new Text(composite,SWT.MULTI|SWT.BORDER|SWT.WRAP|SWT.V_SCROLL);
GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd.heightHint = 2 * text.getLineHeight();
text.setLayoutData(gd);
text.setText("trweghjfbfdshjfghjreuyhjfghkjhjhjsdghjreewhjdfghjhjgfdhjsdghjtreuytrehjdfghjhjdfgh8irtrhjghjhjdfghjdfghjfghjdfg");

Solution

  • Setting widthHint to 0 together with the horizontalAlignment to SWT.FILL makes the text fill all availible space in its column, but not grow more that that. Instead it wraps as desired:

    Screenshot

    I tried this on Windows 10 with SWT 3.103.2. Greg seems to have got another result on Mac.

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    
    Composite composite = new Composite(shell, SWT.NONE);
    composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
    composite.setLayout(new GridLayout(2, false));
    
    Label label = new Label(composite, SWT.LEAD);
    label.setText("Label");
    label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
    
    Text text = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
    GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
    gd.heightHint = 2 * text.getLineHeight();
    
    // Added widthHint
    gd.widthHint = 0;
    text.setLayoutData(gd);
    text.setText("trweghjfbfdshjfghjreuyhjfghkjhjhjsdghjreewhjdfghjhjgfdhjsdghjtreuytrehjdfghjhjdfgh8irtrhjghjhjdfghjdfghjfghjdfg");
    
    shell.pack();
    shell.open();
    
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    
    display.dispose();