Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping SWT Text box size after setting text

Tags:

java

eclipse

swt

When I use setText() on one or both Text fields, it resizes the field to the length of the text. How do I prevent that from happening?

inner = new Composite(middle, SWT.NONE);
inner.setLayout(new GridLayout(5, false));

chkbxBtn = new Button(inner, SWT.CHECK);
chkbxBtn.setText("Check box button: ");
chkbxBtn.setSelection(false);

new Label(inner, SWT.NONE).setText("Text field 1: ");
startCol = new Text(inner, SWT.BORDER | SWT.NONE);

new Label(inner, SWT.NONE).setText("Text field 2: ");
endCol = new Text(inner, SWT.BORDER | SWT.NONE);
like image 408
HiThere Avatar asked Sep 12 '25 02:09

HiThere


2 Answers

To clarify, SWT does not re-layout after changing the text (or any other property) of a Text control (or controls in general). It is your code or a resize event that causes the re-layout.

If you want a control to have a pre-set size, and its parent uses a GridLayout, you can set GridData with a widthHint like this:

GridData gridData = new GridData();
gridData.widthHint = ...
text.setLayoutData( gridData );

However, it is usually a bad idea trying to control the size of widgets. Thus make sure that your layout strategy aligns with best practices of UI design.

like image 118
Rüdiger Herrmann Avatar answered Sep 14 '25 15:09

Rüdiger Herrmann


There are situations when changes to the text trigger a component re-layout. For example, show an error message as a text validation result (I found it in SWT forms). Setting the width hint in the GridData for the text component fixes this. Width hint can be set to 0 or the minimum required size.

    GridDataFactory.swtDefaults()//
            .grab(true, false)//
            .hint(0, SWT.DEFAULT)// width hint prevents text from expanding to full line
            .align(SWT.FILL, SWT.CENTER)//
            .applyTo(text);
like image 35
krab Avatar answered Sep 14 '25 16:09

krab