2013-03-14 64 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

相關問題