简体   繁体   中英

How to make child composite fill parent in swt

Here is my code:

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

    Composite childComposite = new Composite(shell, SWT.BORDER);
    childComposite.setLayout(new GridLayout(2, false));
    Text text1 = new Text(childComposite, SWT.NONE);
    Text text2 = new Text(childComposite, SWT.NONE );

    Label label = new Label(shell, SWT.NONE);
    label.setText("Very loooooooooooooooooooooooong text");

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

This will produce something like this:

在此输入图像描述

My question is how can i make my child composite fill the parent horizontally (be at least the same width that the label below). I tried using something like this:

Composite childComposite = new Composite(shell, SWT.BORDER | SWT.FILL);

... but that didnt change anything.

Also when the child is the same width as parent i want the text widgets to also fill the composite they are in but with different widths - for example the first is 20% and the second is 80%. What possibilities should i check out to accomplish this?

When using GridLayout you use GridData arguments to control setLayoutData methods to specify how the grid is filled.

You want something like:

  shell.setLayout(new GridLayout(1, false));

  Composite childComposite = new Composite(shell, SWT.BORDER);

  // Composite fills the grid row
  childComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));

  // Use 5 equal sized columns
  childComposite.setLayout(new GridLayout(5, true));

  // First text fills the first column
  Text text1 = new Text(childComposite, SWT.NONE);
  text1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));

  // Second text fills the next 4 columns
  Text text2 = new Text(childComposite, SWT.NONE);
  text2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1));

  Label label = new Label(shell, SWT.NONE);
  label.setText("Very loooooooooooooooooooooooong text");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM