0
votes

i needed an Widget to display text properly, containing HTML elements. Therefore i used the GWT HTML-Widget like that.

HTML text= new HTML(new SafeHtml() {

            @Override
            public String asString() {

                return "<b>TestText</b>";
            }
        });

Now i would like to select text displayed by that widget, and somehow get the String.

I would like to right click the marked text, and do something with that String

It's also no problem if your ideas making use of other gwt widgets, i am not too focused on that HTML one.

I also have access to Sencha GXT libarys. Any ideas would be appreciated.

3
You can use SafeHtmlUtils in order to produce SafeHtml objects: gwtproject.org/javadoc/latest/com/google/gwt/safehtml/shared/…Fedy2
I cant see how this helps me to get the selected textJumpingPoint

3 Answers

0
votes

I'm assuming you want the user to select text and then retrieve the selected text on right click. Am I right? I don't recall any way of retrieving selected text in GWT, so I would use pure javascript for that. There is already a thread explaining how to do that with javascript, so you can grab that code and wrap it in a JSNI method:

public class MyClass implements IsWidget {
    private final HTML text;

    public MyClass() {
        text = new HTML(SafeHtmlUtils.fromTrustedString("<b>Some text</b>"));
        text.addDomHandler(new ContextMenuHandler() {
            @Override
            public void onContextMenu(ContextMenuEvent event) {
                String test = getSelection();
                Window.alert(test);
            }
        }, ContextMenuEvent.getType());
    }

    private native String getSelection() /*-{
        var text = "";
        if ($wnd.getSelection) {
            text = $wnd.getSelection().toString();
        } else if ($doc.selection && $doc.selection.type != "Control") {
            text = $doc.selection.createRange().text;
        }
        return text;
    }-*/;

    @Override
    public Widget asWidget() {
        return text;
    }
}
0
votes

You can use sth like this:

final Label label = new Label("Some text");
label.addClickHandler(new ClickHandler() {          
        @Override
        public void onClick(ClickEvent event) {
                label.getElement().getStyle().setBackgroundColor("#ff0"); //sth. like select
                String txt = label.getText(); //get the String
            Window.alert(txt); //do sth. with text

        }
});

But it works on left click. If you have to use right click, you can use native JS code using eg. jQuery click. And do not use b tag. It is deprecated in HTML5.

0
votes

I've actually found a GWT-Libary that can get the selected text. Watch this https://code.google.com/p/gwt-selection/

After installing the libary i just had to

String currentSelection = Selection.getBrowserRange().getText();

Thank you for answering though - you helped me a lot