我有几个链接在JEditorPane中显示,例如:
http://www.google.com/finance?q=NYSE:C
http://www.google.com/finance?q=NASDAQ:MSFT
我希望能够单击它们并在浏览器中显示。
您有什么想法如何做到这一点?
我有几个链接在JEditorPane中显示,例如:
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());
}