Setting the Text Size Limit

There is one more size attribute for text fields that must be mentioned—the number of characters that the text field can contain. There are two aspects of this size. The first is related to how many characters can appear on-screen within the confines of a text box. Users generally do not like single-line text boxes that do not display all the characters in that box. Although the number of characters that can be seen varies greatly with the font size selected (by default, the operating system settings control this), you should attempt to limit the number of characters to a value that can be reasonably expected to fit within the specified bounds of the text field.

The second, and more programmatically important, reason for setting a character limit on a text field is for data validation purposes. Suppose you are designing a GUI that enables the user to submit data for storage in a database. If your text field accepts values that are to be stored in a particular database column, you can decrease the possibility of a database error by limiting input to only the amount of data that is acceptable.

How do I do that?

Setting the character bounds of a Text widget is done by:

text1.setTextLimit(10);

If you add that line to TextFieldExample, you see the effect when you attempt to enter more than 10 characters: you won’t be permitted to do that.

Proper design consists of determining the number of characters you need to allow in a particular field and then using setBounds( ...

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.