Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have text fields fill 100% horizontally

Tags:

java

eclipse

swt

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 ();
    }
}
like image 387
Berlin Brown Avatar asked Jan 12 '09 03:01

Berlin Brown


2 Answers

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.

like image 55
Martin Thurau Avatar answered Nov 01 '22 22:11

Martin Thurau


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.

like image 5
Mario Ortegón Avatar answered Nov 01 '22 21:11

Mario Ortegón