What is the appropriate listener to use for Eclipse SWT Text?

eclipse-plugin, java, swt

Solution

I think `SWT.MouseUp` is the event you are looking for. If you want to check "arrow keys and shift selection", listen to `SWT.KeyUp` as well and check the `keyCode` of the event:

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

    Text text = new Text(shell, SWT.BORDER);
    text.setText("BLABLABLA");

    text.addListener(SWT.MouseUp, new Listener() {

        @Override
        public void handleEvent(Event event) {
            Text text = (Text) event.widget;

            String selection = text.getSelectionText();

            if(selection.length() > 0)
            {
                System.out.println("Selected text: " + selection);
            }
        }
    });

    text.addListener(SWT.KeyUp, new Listener() {

        @Override
        public void handleEvent(Event event) {
            Text text = (Text) event.widget;

            String selection = text.getSelectionText();

            if(selection.length() > 0 && event.keyCode == SWT.SHIFT)
            {
                System.out.println("Selected text: " + selection);
            }
        }
    });

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

This code will only print the selection, if the user really selected something. If it's a mouse-up o key-up without selection, nothing will happen.

You might want to combine both in one listener to save space.

Problem

I have a class of this type `org.eclipse.swt.widgets.Text`. It lives inside of an eclipse plugin I am developing. I want to handle the event where the user selects text from within this field. That is... while focused, they click into some text and drag either left or right to select text. When this text is selected, that is when I need to fire my event. I am yet unable to find the appropriate listener to cover my need.

Original source