Nitish Borade Nitish Borade - 10 days ago 5
Java Question

How to setcursor position in GWT RichTextArea

Is there a way to set the cusror position in GWT RichTextArea. There is method setCusrorPosition() to do so in TextArea, but not in RichTextArea.
Perhaps there is a native JavaScript (called from GWT) that could set the cursor position in the RichTextArea?

Answer

You are right RichTextArea is not providing the setSelectionRange method, but i have created one using the JSNI.

Below is the method,

public native void setSelectionRange(Element elem, int pos, int length) /*-{
    try {
        var selection = null, range2 = null;
        var iframeWindow = elem.contentWindow;
        var iframeDocument = iframeWindow.document;

        selection = iframeWindow.getSelection();
        range2 = selection.getRangeAt(0);

        //create new range
        var range = iframeDocument.createRange();
        range.setStart(selection.anchorNode, pos);
        range.setEnd(selection.anchorNode, length);

        //remove the old range and add the newly created range
        if (selection.removeRange) { // Firefox, Opera, IE after version 9
            selection.removeRange(range2);
        } else {
            if (selection.removeAllRanges) { // Safari, Google Chrome
                selection.removeAllRanges();
            }
        }
        selection.addRange(range);
    } catch (e) {
        $wnd.alert(e);
    }
}-*/;

For using above method write below code:

final RichTextArea tr = new RichTextArea();
    Button b = new Button("Test");
    b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            setSelectionRange(tr.getElement(), 15, 20);
            tr.setFocus(true);
        }
    });
    RootPanel.get().add(tr);
    RootPanel.get().add(b);

Note: Do remember to put the validation checks of "pos" and "length" you are passing in setSelectionRange() method. This code had been tested in IE9, FF, Chrome.