I have been stuck with the problem of making UI widgets fill horizontally in a grid layout a few times. The solution is simple, but when I have to create UI using Eclipse SWT after a long gap, I tend to forget how I had made this work earlier, so I decided to blog about this.
I had to create a simple UI with one label and associated text box. I coded it like this –
GridLayout layout = new GridLayout(2, false); tabContainer.setLayout(layout); //this is the parent composite Label label1 = new Label(tabContainer, SWT.NONE); label1.setText("Some Label:"); GridData gd = new GridData(); gd.grabExcessHorizontalSpace = false; label1.setLayoutData(gd); Text txtBox1 = new Text(tabContainer, SWT.BORDER); gd = new GridData(); gd.grabExcessHorizontalSpace = true; txtBox1.setLayoutData(gd);
UI created by the above code is –
With grabExcessHorizontalSpace attribute of GridData set to true, I was expecting text box to fill the horizontal space. JavaDoc for this attribute says – “grabExcessHorizontalSpace specifies whether the width of the cell changes depending on the size of the parent Composite”. So I thought it should be enough to make text box fill horizontal space. But it did not.
After digging into previously written code for similar UI, I found that I had to set another attribute to make it work. I had to set gd.horizontalAlignment = SWT.FILL;
Text txtBox1 = new Text(tabContainer, SWT.BORDER); gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = SWT.FILL; txtBox1.setLayoutData(gd);
The above change generated the UI that I was expecting –
I think name ‘horizontalAlignment’ is confusing – JavaDoc says : “horizontalAlignment specifies how controls will be positioned horizontally within a cell. The default value is BEGINNING”. So you might think that this attribute controls position of the widget in the cell, but it also has a value that controls its size (SWT.FILL).
Note that both the attributes, grabExcessHorizontalSpace and horizontalAlignment, have to be set to make this work.
So next time I face the same problem, I will remember to refer to this post.