How to put an ImageIcon in a JLabel that contains a hyperlink?

499 views Asked by At

I'm writing a UI using Java Swing, and I need to have a picture that, when clicked, takes the user to a specific webpage.

So far, the other images I've been adding to my project have been done using

JLabel myImage = new JLabel(new ImageIcon("filePath\\imagename.png"));

But now that this specific image needs to contain a hyperlink, I can't figure out whether it's possible to embed a link using the above JLabel/ImageIcon approach.

As an alternative approach, I thought an HtmlPanel would be the way to go, but I can't get an image to show that way. The following code gives me a broken image, but which is clickable and takes me to my webpage:

HtmlPanel myImage = new HtmlPanel("<a href='http://myWebsite.com'> <img src='filepath\\fileName.png' alt='blahblah'></a>");

Any advice would be greatly appreciated! (P.S. I'm relatively new to programming in general, so if your answers could contain example code, that would be extra helpful, since most people's answers go way over my head)

1

There are 1 answers

1
Programmer On BEST ANSWER

For this you have to add mouse listener in JLabel label which contains ImageIcon means your image.

Here is the Code :

    Icon i1 = new ImageIcon(getClass().getResource("image.jpg"));
    l4 = new JLabel(i1);

    l4.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {

            String command = "rundll32 url.dll,FileProtocolHandler https://www.google.com";
            try {
                Process p = Runtime.getRuntime().exec(command);

            } catch (Exception e1) {

                JOptionPane.showMessageDialog(null, "\n Error! \n");

            }

        }
    });
    add(l4);