cosimo
cosimo

Reputation: 41

How to make the text in an SWT Link widget selectable

I have a text in the Link SWT widget created as follow:

Link message = new Link(parent, SWT.WRAP);
message.setText(myMessage);

I want the text (in myMessage variable) be selectable, to grant users to copy it. How can I do this?

I have used Link widget because I need hyperlinks in the text to be clickable.

Upvotes: 4

Views: 1322

Answers (2)

Rüdiger Herrmann
Rüdiger Herrmann

Reputation: 21025

The SWT Link widget is not selectable. To work around this I can think of either

  1. provide a context menu for the Link with a Copy menu item that copies the text to the clipboard
  2. place a Copy (tool) button next to the Link that copies the text to the clipboard
  3. use a Browser widget which is selectable but harder to layout and requires extra work to trigger the functinality when the link is selected
  4. if you don't mind the extra dependency to org.eclipse.ui.forms, use the FormText. The FormText can show hyperlinks and allows to select and copy text

Upvotes: 3

fluminis
fluminis

Reputation: 4099

Why not using a StyledText to allow text selection ?

String string = "This is sample text with a link and some other link here.";
final StyledText styledText = new StyledText (shell, SWT.MULTI | SWT.BORDER);
styledText.setText(string);

String link1 = "link";
String link2 = "here";
StyleRange style = new StyleRange();
style.underline = true;
style.underlineStyle = SWT.UNDERLINE_LINK;

int[] ranges = {string.indexOf(link1), link1.length(), string.indexOf(link2), link2.length()}; 
StyleRange[] styles = {style, style};
styledText.setStyleRanges(ranges, styles);

styledText.addListener(SWT.MouseDown, new Listener() {
    @Override
    public void handleEvent(Event event) {
        // It is up to the application to determine when and how a link should be activated.
        // In this snippet links are activated on mouse down when the control key is held down 
        if ((event.stateMask & SWT.MOD1) != 0) {
            try {
                int offset = styledText.getOffsetAtLocation(new Point (event.x, event.y));
                StyleRange style = styledText.getStyleRangeAtOffset(offset);
                if (style != null && style.underline && style.underlineStyle == SWT.UNDERLINE_LINK) {
                    System.out.println("Click on a Link");
                }
            } catch (IllegalArgumentException e) {
                // no character under event.x, event.y
            }

        }
    }
});

Full example here

Upvotes: 2

Related Questions