Add hyperlink onclick listener to JEditorPane

718 views Asked by At

I'd like to add an hyperlink onclick listener to a simple web page displayed inside a JEditorPane. I have the following code but it is not working

  JEditorPane jep = new JEditorPane();
    jep.setEditable(false);   
    String currenturl="http://www.newsite.com";
    try {
        jep.addHyperlinkListener(this);
      jep.setPage(currenturl);

    }catch (IOException e) {
      jep.setContentType("text/html");
      jep.setText("<html>Could not load</html>");
    }

Does anyone have an idea on how to do this ?

1

There are 1 answers

1
StanislavL On

Before adding listener the JEditorPane should have EditorKit (content type "text/html" sets HTMLEditorKit which can provide logic to process URL clicks). Also the JEditorPane must not be editable.

so call

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

before adding the listener

UPDATE: if you wuld like to process links in editable JEditorPane check this