【问题标题】:SWT: Integrate clickable link into StyledTextSWT:将可点击链接集成到 StyledText
【发布时间】:2018-08-07 20:25:30
【问题描述】:

this question 的帮助下,我能够弄清楚如何在 SwT 中的 StyledText 小部件中显示链接。颜色是正确的,当鼠标悬停在链接上时,甚至光标也会改变形状。

到目前为止一切顺利,但该链接实际上不可点击。虽然光标改变了它的形状,但如果点击链接,什么都不会发生。因此,我在问如何单击链接以在浏览器中实际打开它。

我曾想过使用MouseListener,将点击位置跟踪回执行点击的相应文本,然后决定是否打开链接。然而,这似乎太复杂了,因为已经有一些程序可以相应地更改光标。我相信有一些简单的方法可以做到这一点(并确保点击行为实际上与光标改变其形状时一致)。

有人有什么建议吗?

这是一个 MWE,展示了我到目前为止所做的事情:

public static void main(String[] args) throws MalformedURLException {
final URL testURL = new URL("https://stackoverflow.com/questions/1494337/can-html-style-links-be-added-to-swt-styledtext");

Display display = new Display();

Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, true));

StyledText sTextWidget = new StyledText(shell, SWT.READ_ONLY);

final String firstPart = "Some text before ";
String msg = firstPart + testURL.toString() + " some text after";

sTextWidget.setText(msg);
sTextWidget.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

StyleRange linkStyleRange = new StyleRange(firstPart.length(), testURL.toString().length(), null, null);
linkStyleRange.underline = true;
linkStyleRange.underlineStyle = SWT.UNDERLINE_LINK;
linkStyleRange.data = testURL.toString();

sTextWidget.setStyleRange(linkStyleRange);

shell.open();

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

【问题讨论】:

    标签: hyperlink swt


    【解决方案1】:

    好的,我发布这个问题的速度有点太快了...有一个 sn-p 可以解决这个问题,它表明,确实必须使用额外的 MouseListener 才能使事情正常进行.

    sn-p 可以在here 找到,这是设置监听器的相关部分:

    styledText.addListener(SWT.MouseDown, 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) {
            int offset = styledText.getOffsetAtLocation(new Point (event.x, event.y));
            if (offset != -1) {
                StyleRange style1 = null;
                try {
                    style1 = styledText.getStyleRangeAtOffset(offset);
                } catch (IllegalArgumentException e) {
                    // no character under event.x, event.y
                }
                if (style1 != null && style1.underline && style1.underlineStyle == SWT.UNDERLINE_LINK) {
                    System.out.println("Click on a Link");
                }
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2012-08-10
      • 2011-05-29
      相关资源
      最近更新 更多