Reacting to Text Events

Sometimes the underlying business logic of your application requires that you respond to events that occur when the user interacts with a text field. One example is when you must perform validation on the field’s contents before you enable the user to move away from the field to another widget on the window. Another example is the popular interface feature that causes text in a field to become selected whenever the field gains focus.

As with the MenuItem and ToolItem classes, for a text field to respond to an event a Listener must be added to the Text object. Text objects can respond to one of three text-specific listener types:

  • ModifyListener , which fires whenever the text in the field is altered

  • SelectionListener , which fires whenever the text in the field is selected

  • VerifyListener , which fires when the text in the field is about to be modified, but before the modification becomes visible to the user

Text fields can also respond to a number of more generic events that are defined as being applicable to all widgets.

Note

The add( ) methods for these events are defined in the Control class, which is the ancestor to almost all widgets.

One of the more commonly used events for text fields is the focus event. Focus events occur whenever the text field gains or loses the input focus. This is most commonly caused by the user tabbing or clicking between fields. The focus event is a good place to perform field-level validation or to select text on entry.

How do ...

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.