2013-03-14 24 views
2

我有下面的代码中添加HTML到JEditorPane如何在JEditorPane clikcable中添加锚标记? (JAVA)

 JEditorPane content = new JEditorPane(); 

     content.setEditable(false); 
     content.setContentType("text/html"); 

     content.setText(resultText); 

     JScrollPane bottomScrollPane = new JScrollPane(content); 
     bottomScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
     bottomScrollPane.setBorder(BorderFactory.createTitledBorder("Swing Rendered")); 

这一步后,我已经添加了JEditorPane的实例“内容”到一个JPanel实例和 可以能够完美地看到结果。但是当我尝试点击显示的链接时,它不起作用。

如何使这些链接可点击,并且它应该将用户重定向到浏览器中的特定网址?

问候, 巴兰

回答

6

您需要HyperlinkListener添加到JEditorPane中:

pane.addHyperlinkListener(new HyperlinkListener() 
{ 
    public void hyperlinkUpdate(HyperlinkEvent r){ 
     try{ 
      if(r.getEventType() == HyperlinkEvent.EventType.ACTIVATED) 
      pane.setPage(r.getURL()); 
     } 
     catch(Exception e){ 
     } 
    } 
}); 

或者,你可以做任何事情在听者...例如,在默认浏览器中打开链接:

您需要HyperlinkListener添加到JEditorPane中:

pane.addHyperlinkListener(new HyperlinkListener() 
{ 
    public void hyperlinkUpdate(HyperlinkEvent r){ 
     try{ 
      if(r.getEventType() == HyperlinkEvent.EventType.ACTIVATED) 
      Desktop.getDesktop().browse(new URI(r.getURL().toURI())); 
     } 
     catch(Exception e){ 
     } 
    } 
}); 
+0

我试过这段代码,我想让链接在浏览器窗口中打开..不是内嵌在窗格中.. – balanv 2013-03-14 10:30:36

+0

@balanv请参阅编辑 – 2013-03-14 10:33:50

+0

非常感谢.. +1 for swift help .. – balanv 2013-03-14 10:54:04

相关问题