代码之家  ›  专栏  ›  技术社区  ›  Raven Bill Karwin

SWT:将可点击链接集成到StyledText中

  •  0
  • Raven Bill Karwin  · 技术社区  · 8 年前

    借助于 this question 我能找出如何在 StyledText SwT中的小部件。当光标悬停在链接上时,颜色是正确的,甚至光标也会改变形状。

    到目前为止还不错,但链接实际上是不可点击的。尽管光标改变了它的形状,但是如果单击链接,什么也不会发生。因此,我问我如何才能使点击链接,实际上打开它在浏览器。

    我想用一个 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();
    }
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Raven Bill Karwin    8 年前

    好吧,我发这个问题有点太快了。。。有一个片段正好处理了这个问题,它表明,一个人确实需要使用一个额外的 MouseListener 为了让事情顺利进行。

    可以找到片段 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");
                }
            }
        }
    });