views:

605

answers:

2

If I have a text field with SWT, how can I get the field to fill to 100% or some specified width.

For example, this text field will only reach for so much horizontally.

public class Tmp {
    public static void main (String [] args) {
     Display display = new Display ();
     Shell shell = new Shell (display);
     GridLayout gridLayout = new GridLayout ();
     shell.setLayout (gridLayout);

     Button button0 = new Button(shell, SWT.PUSH);
     button0.setText ("button0");

     Text text = new Text(shell, SWT.BORDER | SWT.FILL);
     text.setText ("Text Field");

     shell.setSize(500, 400);
     //shell.pack();
     shell.open();

     while (!shell.isDisposed ()) {
      if (!display.readAndDispatch ())
       display.sleep ();
     }
     display.dispose ();
    }
}
+1  A: 

Make something like this:

Text text = new Text(shell, SWT.BORDER);
text.setText ("Text Field");
text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER));

/: Since this is the accepted answer I remove the errors. Thx for correcting me.

Martin
Constructor GridData(int) is deprecated.Use "new GridData(SWT.FILL, SWT.CENTER)" instead
qualidafial
You should not reuse GridData objects since they act as caches for grid cell calculations. GridData reuse can lead to layout bugs where several components sharing a common GridData are truncated to the size of the most small-size one. This is in the GridData's javadoc.
Altherac
+2  A: 

Positioning of elements in a Component depends on the Layout object that you are using. In the sample provided, you are using a GridLayout. That means, that you need to provide a specific LayoutData object to indicate how you want your component displayed. In the case of GridLayout, the object is GridData.

To achieve what you want, you must create a GridData object that grabs all horizontal space and fills it:

// Fills available horizontal and vertical space, grabs horizontal space,grab
// does not  grab vertical space
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
text.setLayoutData(gd);

Alternative ways include using a different LayoutManager, such as FormLayout. This layout uses a FormData object that also allows you to specify how the component will be placed on the screen.

You can also read this article on Layouts to understand how Layouts work.

As a side note, the constructor new GridData(int style) is marked as "not recommended" in the documentation. The explicit constructor shown in this example is preferred instead.

Mario Ortegón