我在 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
我希望我应该能够单击它们并且它会显示在浏览器中
有什么想法如何去做吗?
这有几个部分:
正确设置 JEditorPane
The 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 http://download.oracle.com/javase/7/docs/api/javax/swing/event/HyperlinkListener.html对付他们:
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 http://download.oracle.com/javase/6/docs/api/java/awt/Desktop.html class:
if(Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(e.getURL().toURI());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)