JEdi​​torPane中的超链接 [英] Hyperlink in JEditorPane

查看:226
本文介绍了JEdi​​torPane中的超链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JEditorPane ex中显示的链接很少:

I have few links displayed in JEditorPane ex:

http://www.google.com/finance?q=NYSE:C

http://www.google.com/finance?q=NASDAQ:MSFT

我希望我能够点击它们并将其显示在浏览器中

I want that I should be able to click them and that it gets displayed in browser

任何想法如何做?

推荐答案

这里有几个部分:

JEditorPane 需要上下文类型 text / html ,并且它对于可点击的链接是不可编辑的:

The JEditorPane needs to have the context type text/html, and it needs to be uneditable for links to be clickable:

final JEditorPane editor = new JEditorPane();
editor.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editor.setEditable(false);



添加链接



您需要将实际的< a> 标签添加到编辑器中,以便将它们呈现为链接:

Add the links

You need to add actual <a> tags to the editor for them to be rendered as links:

editor.setText("<a href=\"http://www.google.com/finance?q=NYSE:C\">C</a>, <a href=\"http://www.google.com/finance?q=NASDAQ:MSFT\">MSFT</a>");



添加链接处理程序



默认情况下点击链接不会做任何事情;你需要一个 HyperlinkListener 处理它们:

Add the link handler

By default clicking the links won't do anything; you need a HyperlinkListener to deal with them:

editor.addHyperlinkListener(new HyperlinkListener() {
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
           // Do something with e.getURL() here
        }
    }
});

如何启动浏览器来处理 e.getURL()由您决定。如果您使用的是Java 6和支持的平台,那么使用 桌面 类:

How you launch the browser to handle e.getURL() is up to you. One way if you're using Java 6 and a supported platform is to use the Desktop class:

if(Desktop.isDesktopSupported()) {
    Desktop.getDesktop().browse(e.getURL().toURI());
}

这篇关于JEdi​​torPane中的超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆