java JEditorPane 中的超链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3693543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hyperlink in JEditorPane
提问by Mohit Bansal
I have few links displayed in JEditorPane ex:
我在 JEditorPane ex 中显示的链接很少:
http://www.google.com/finance?q=NYSE:C
http://www.google.com/finance?q=NYSE:C
http://www.google.com/finance?q=NASDAQ:MSFT
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
我希望我应该能够点击它们并显示在浏览器中
Any ideas how to do it?
任何想法如何做到?
回答by Michael Mrozek
There's a few parts to this:
这有几个部分:
Setup the JEditorPane correctly
正确设置 JEditorPane
The JEditorPane
needs to have the context type text/html
, and it needs to be uneditable for links to be clickable:
在JEditorPane
需要有上下文类型text/html
,并且它需要不可编辑的链接,可以点击:
final JEditorPane editor = new JEditorPane();
editor.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editor.setEditable(false);
Add the links
添加链接
You need to add actual <a>
tags to the editor for them to be rendered as links:
您需要向<a>
编辑器添加实际标签,以便将它们呈现为链接:
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>");
Add the link handler
添加链接处理程序
By default clicking the links won't do anything; you need a HyperlinkListener
to deal with them:
默认情况下,点击链接不会做任何事情;你需要一个HyperlinkListener
来处理它们:
editor.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
// Do something with e.getURL() here
}
}
});
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:
您如何启动浏览器来处理e.getURL()
取决于您。如果您使用的是 Java 6 并且受支持的平台,一种方法是使用Desktop
该类:
if(Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(e.getURL().toURI());
}