SWT Text Focus and default selection(return key) events

nbz picture nbz · May 29, 2013 · Viewed 7.3k times · Source

I am having a strange problem on my RCP. I don't use Linux to develop so my knowledge for common bugs is very less. I am using Ubuntu 11.10 to try out the RCP.

In my RCP, I have an SWT Text that has two listeners attached to it - one for focus (FocusAdapter) and the other for SWT.DefaultSelection. In the FocusAdapter, I implement the focusLost method.

The behaviour is such, if and when the user edits the text and hits the return key, then the SWT.DefaultSelection listener's handleEvent will be called and display a message to confirm the new text and update the Text field. If the user edits the text but does NOT hit the return key and simply clicks outside the Text field, then the focusLost event is called which reverts the text back to the original text (text.setText(originalText);).

This seems to work fine when I launch it from Eclipse but when I export the product via Maven+Tycho, that behaviour seems to stop working. What happens is that when the user edits the text, it just reverts back to the original text irrespective of whether the user hits the return key or not, or simply clicks outside the Text field. No message dialog to confirm the edited text is displayed either.

From what I gather it seems to just use the focusLost event and the return key has no effect. I apologise if this is something obvious but I have not encountered this on a windows machine which is what I use for my primary development.

Answer

Baz picture Baz · May 29, 2013

You can listen for SWT.Traverse instead and check if event.detail equals SWT.TRAVERSE_RETURN. I tested it on Linux and it works:

public static void main(String[] args)
{
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    final Text text = new Text(shell, SWT.BORDER);
    text.addListener(SWT.Traverse, new Listener()
    {
        @Override
        public void handleEvent(Event event)
        {
            if(event.detail == SWT.TRAVERSE_RETURN)
            {
                System.out.println("Enter pressed");
            }
        }
    });

    shell.pack();
    shell.open();

    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
        {
            display.sleep();
        }
    }
    display.dispose();
}

There is a related question here:

SWT Cross-Platform Enter Detection