anup r
anup r

Reputation: 121

How to limit the size of text field in SWT?

I have a Text control and GridLayout associated with it.

When I create it, a text field is created with certain width. When I enter text in the text field and save, I will update the model. Again if I close that particular view and open it again, the text field is expanded with the width of the text entered earlier.

How to limit this and provide a particular width to the text box so that it doesn't expand further?

Upvotes: 0

Views: 2059

Answers (1)

greg-449
greg-449

Reputation: 111217

Use the widthHint field of the GridData to specify the control width.

At its simplest this would be:

Text text = new Text(....);

GridData data = new GridData(SWT.BEGINNING, SWT.CENTER, false, false);

data.widthHint = 100;  // Some width

text.setLayoutData(data);

If you are doing this in a class derived from Dialog you can use

data.widthHint = convertWidthInCharsToPixels(10);  // Some number of characters

to specify the width in characters.

Outside of dialog you can use:

GC gc = new GC(text);

gc.setFont(text.getFont());

FontMetrics fontMetrics = gc.getFontMetrics();

data.widthHint = fontMetrics.getAverageCharWidth() * chars;

gc.dispose();

Upvotes: 3

Related Questions