【发布时间】:2011-04-11 05:57:57
【问题描述】:
JEditorPane ex 中显示的链接很少:
http://www.google.com/finance?q=NYSE:C
http://www.google.com/finance?q=NASDAQ:MSFT
我希望我应该能够点击它们并显示在浏览器中
有什么办法吗?
【问题讨论】:
JEditorPane ex 中显示的链接很少:
http://www.google.com/finance?q=NYSE:C
http://www.google.com/finance?q=NASDAQ:MSFT
我希望我应该能够点击它们并显示在浏览器中
有什么办法吗?
【问题讨论】:
这有几个部分:
JEditorPane 需要具有上下文类型text/html,并且它需要不可编辑才能使链接可点击:
final JEditorPane editor = new JEditorPane();
editor.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editor.setEditable(false);
您需要在编辑器中添加实际的<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>");
默认情况下点击链接不会做任何事情;你需要HyperlinkListener 来处理它们:
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 和受支持的平台,一种方法是使用 Desktop 类:
if(Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(e.getURL().toURI());
}
【讨论】: