How do I change a cursor when the mouse moves over a hyperlink in a JTextPane?

Jan Borchers

Just add a HyperlinkListener to your JEditorPane/JTextPane component. The sample below also manages clicks on hyperlinks.


...
JEditorPane pane = new JEditorPane();
pane.setEditable(false);
pane.setEditorKit(new HTMLEditorKit());
pane.addHyperlinkListener(new HyperlinkListenerImpl());
...

protected class HyperlinkListenerImpl
  implements HyperlinkListener
{
  public void hyperlinkUpdate(HyperlinkEvent event)
  {
    JEditorPane pane = (JEditorPane)event.getSource();
    HyperlinkEvent.EventType type = event.getEventType();

    if(type == HyperlinkEvent.EventType.ENTERED){

      pane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    }else if(type == HyperlinkEvent.EventType.EXITED){

      pane.setCursor(Cursor.getDefaultCursor());

    }else if(type == HyperlinkEvent.EventType.ACTIVATED){

      pane.setCursor(Cursor.getDefaultCursor());

      if(event instanceof HTMLFrameHyperlinkEvent){

        HTMLDocument doc = (HTMLDocument)pane.getDocument();
        doc.processHTMLFrameHyperlinkEvent((HTMLFrameHyperlinkEvent)event);

      }else{

        try{
          pane.setPage(event.getURL());
        }catch(IOException ex){
          ex.printStackTrace();
        }
      }
    }
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact