Search code examples
javaswingjtextpane

How can I make image link work in JtextPane?


I want to give a image link on my pc to a row on jtextpane. I give "text/html" ttype to jtextpane

 jTextPane1.setContentType("text/html");  

and I wrote this code for give image:

html text:

<img src=  file:/"+myimageplace+" alt=\"Click to Open Image\" width=\"30\" height=\"30\">

this is working for showing image.

But I want to give that image to go to image like this :

<a href=\"file:/"+myimageplace+">\"<img src=  file:/"+mytext+" alt=\"Click to Open Image\" width=\"30\" height=\"30\"></a>

But this isnt working?

How can I do that? Thanks.


Solution

  • You need to have an event/link handler related to link clicks for this to work. Even though your rendering HTML, without a specific link handler to handle clicks it will not open the window.

    I am quoting from here: Hyperlink in JEditorPane

    Add the link handler

    By default clicking the links won't do anything; you need a HyperlinkListener to deal with them:

    editor.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
               // Do something with e.getURL() here
            }
        }
    });
    

    How you launch the browser to handle e.getURL() is up to you. One way if you're using Java 6 and a supported platform is to use the Desktop class:

    if(Desktop.isDesktopSupported()) {
        Desktop.getDesktop().browse(e.getURL().toURI());
    }