Wrapping Text

If you run Example 5-3, you see that entering text in the field does not yield exactly the anticipated results. If you enter more text than can be displayed in the field, the text does not wrap to the next line; it just disappears off somewhere to the right. This continues until you press Enter to drop to the next line.

Note

Users generally expect text to wrap to the next line when one line is filled.

How do I do that?

As you might expect, creating a field that wraps is just a matter of specifying another style attribute, SWT.WRAP :

final Text text1 = new Text(s, SWT.MULTI | SWT.WRAP | SWT.BORDER);

Changing Example 5-3 to construct a wrapping text field will result in Figure 5-5.

Wrapping text

Figure 5-5. Wrapping text

What about...

times when you need to change the style of a text field from wrapping to nonwrapping, or even from single-line to multiline. This isn’t possible using the SWT, since those styles are specified at the time the widget is created. A workaround is to create two separate widgets, one with each style, then hide or show them as needed:

final Text text1 = new Text(s, SWT.MULTI | SWT.WRAP |SWT.BORDER);
text1.setBounds(100,50,100,100);
text1.setVisible(true);
final Text text2 = new Text(s, SWT.MULTI | SWT.BORDER);
text2.setBounds(100,50,100,100);
text2.setVisible(false);

When the nonwrapping version is needed, you do this:

text1.setVisible(false); text2.setVisible(true); ...

Get SWT: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.