Search code examples
javaimageswingurljeditorpane

Clickable images using JEditorPane in a JFrame that opens the associated URL


Hi I am trying to present user with a simple Jframe where the user sees images of the top 10 MMO's. I already have a simple html file where the images bring the user to the correct games web URL.

    public static void main(String[] args) throws Exception {
    String url = "exmaple web address etc http//..";
    JEditorPane editor = new JEditorPane(url);
    editor.setEditable(false);
    JScrollPane pane = new JScrollPane(editor);
    JFrame frame = new JFrame("Top 10 MMO's");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(pane);
    frame.setSize(400, 300);
    frame.setVisible(true);

    public void HyperLinked(HyperlinkEvent e) throws URISyntaxException {
    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
        if (Desktop.isDesktopSupported()) {
            try {
                Desktop.getDesktop().browse(e.getURL().toURI());
            } catch (IOException | URISyntaxException e1) {
            }
        }
    }
}

Example html code the contains images each with its own clickable web adress

            </p>
            <p>
                <h4>Dungeons and Dragons</h4>
                <a href="http://www.ddo.com/" target="_blank"><img src="images/ddo.jpg" alt="Dungeons and Dragons Online" width="351" height="144" border="0" /></a>
            </p>
            <p>
                <h4>Lord of the Rings</h4>
                <a href="http://www.lotro.com/en?lang=en_GB&" target="_blank"><img src="images/lotro.jpg" alt="Lord of the Rings" width="351" height="144" border="0" /></a>
            </p>
            <p>
                <h4>Aion</h4>
                <a href="http://www.aionfreetoplay.com/website/" target="_blank"><img src="images/aion.jpg" alt="Aion" width="351" height="144" border="0" /></a>
            </p>
            <p>

Image example below am not allowed post as new user rules etc http://s14.postimage.org/7xt52lbox/mmoset.jpg

I am able to display the images and I know they are clickable and work its just in the JFrame I am unable to click on them, wondering do I need to add a mouse click or something?

I'd appreciate feedback or some help, thanks!


Solution

  • You almost got it.

        editor.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(HyperlinkEvent e) {
                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                    if (Desktop.isDesktopSupported()) {
                        try {
                            Desktop.getDesktop().browse(e.getURL().toURI());
                        } catch (IOException | URISyntaxException e1) {
                        }
                    }
                }
            }
        });