SWT confusion about events triggered on a TextField by CR/Return

50 Views Asked by At

I am fairly new to SWT and found that pressing "Return" on a TextField does (at least) three things: create an event for SWT.KeyUp, some microseconds later, an event for SWT.Dispose, and, SWT.DefaultSelection, the later two with (accidentally?) the same timestamp.

I mistakenly thought this would be only one event, being consumed by the first handler that received it.

Now my KeyUp-event is received by a Listener that is not intended to get it, as what should happen is already handled via the dispose and default handlers.

Question is: how to detect such situations and tell the Listener watching for "Return" to ignore this event?


I have finally found the cause, which were really two:

firstly, I checked event.character == SWT.CR instead of event.keyKode == SWT.CR.

Second, in my SWT.DefaultSelection-listener I called dispose() on the text field. Naturally, the disposed Text-field didn't have focus any more and the SWT.KeyUp event loaded with the CR was received by a different widget that happened to have the focus (a TabFolder in my case).

It looks like the listeners are processed in the sequence order in which they are added to a widget, but I can't find reference it this is by chance, implementation dependent or by design.

1

There are 1 best solutions below

4
greg-449 On

To stop a Return in a Text field being processed use a traverse listener on the text:

Text text = ....

text.addListener(SWT.Traverse, event ->
 {
    if (event.detail == SWT.TRAVERSE_RETURN)
      event.doit = false;
 });