JEdi​​torPane中的超链接

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

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

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

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

有什么想法怎么做?

这有几个部分:

正确设置JEditorPane

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

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

添加链接

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

 editor.setText("C, MSFT"); 

添加链接处理程序

默认情况下,单击链接将不会执行任何操作; 你需要一个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()); }