user758795
user758795

Reputation: 449

Set fixed size for group SWT

I have a page with some Groups. In the groups I placed some labels with different text. I want all the groups to have the same size. How can I do it? (I tried the setSize function but it did not work for me).

Upvotes: 1

Views: 3957

Answers (1)

Baz
Baz

Reputation: 36884

The following code does what you want. The trick consists of two parts:

  • Same width: The parent (in this example the Shell) uses a GridLayout where each column has the same width
  • Same height: We use GridData to tell each Group to take up the whole height of the parent (the Shell).

public class StackExample
{
    public static void main(String[] args)
    {
        Display display = Display.getDefault();
        final Shell shell = new Shell(display);
        shell.setLayout(new GridLayout(3, true));
        shell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        for(int i = 0; i < 3; i++)
        {
            createGroup(shell, i);
        }

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

    private static void createGroup(Shell parent, int index)
    {
        Group group = new Group(parent, SWT.NONE);
        group.setText("Group " + index);
        group.setLayout(new GridLayout(1, false));
        group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        for(int i = 0; i < index + 1; i++)
        {
            String text = "";
            for(int j = 0; j < index + 1; j++)
            {
                text += "text";
            }

            Label label = new Label(group, SWT.NONE);
            label.setText(text);
            label.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
        }
    }
}

Here are two screenshots:

Smallest size:

enter image description here

When increasing the window size:

enter image description here

Upvotes: 6

Related Questions