如何将 ImageIcon 放入包含超链接的 JLabel 中?
How to put an ImageIcon in a JLabel that contains a hyperlink?
我正在使用 Java Swing 写一个 UI,我需要一张图片,当点击时,将用户带到一个特定的网页。
到目前为止,我添加到项目中的其他图像都是使用
完成的
JLabel myImage = new JLabel(new ImageIcon("filePath\imagename.png"));
但是现在这个特定的图像需要包含一个 hyperlink,我不知道是否可以使用上面的 JLabel/ImageIcon 方法嵌入 link。
作为替代方法,我认为 HtmlPanel 是可行的方法,但我无法获得显示该方法的图像。下面的代码给了我一个破损的图像,但它是可点击的并带我到我的网页:
HtmlPanel myImage = new HtmlPanel("<a href='http://myWebsite.com'> <img src='filepath\fileName.png' alt='blahblah'></a>");
如有任何建议,我们将不胜感激! (P.S。总的来说,我对编程还比较陌生,所以如果您的答案可以包含示例代码,那将非常有帮助,因为大多数人的答案都超出了我的理解范围)
为此,您必须在 JLabel 标签中添加鼠标侦听器,其中包含 ImageIcon 表示您的图像。
这是代码:
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);
我正在使用 Java Swing 写一个 UI,我需要一张图片,当点击时,将用户带到一个特定的网页。
到目前为止,我添加到项目中的其他图像都是使用
完成的JLabel myImage = new JLabel(new ImageIcon("filePath\imagename.png"));
但是现在这个特定的图像需要包含一个 hyperlink,我不知道是否可以使用上面的 JLabel/ImageIcon 方法嵌入 link。
作为替代方法,我认为 HtmlPanel 是可行的方法,但我无法获得显示该方法的图像。下面的代码给了我一个破损的图像,但它是可点击的并带我到我的网页:
HtmlPanel myImage = new HtmlPanel("<a href='http://myWebsite.com'> <img src='filepath\fileName.png' alt='blahblah'></a>");
如有任何建议,我们将不胜感激! (P.S。总的来说,我对编程还比较陌生,所以如果您的答案可以包含示例代码,那将非常有帮助,因为大多数人的答案都超出了我的理解范围)
为此,您必须在 JLabel 标签中添加鼠标侦听器,其中包含 ImageIcon 表示您的图像。
这是代码:
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);