I\'m using a JOptionPane to display some product information and need to add some links to web pages.
I\'ve figured out that you can use a JLabel containing html, so
The solution proposed below the answer does not work with Nimbus Look and Feel. Nimbus overrides the background color and makes the background white. The solution is to set the background color in the css. You also need to remove the component border. Here is a class that implements a solution that works with Nimbus (I Did not check other L&F):
import java.awt.Color;
import java.awt.Font;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class MessageWithLink extends JEditorPane {
private static final long serialVersionUID = 1L;
public MessageWithLink(String htmlBody) {
super("text/html", "<html><body style=\"" + getStyle() + "\">" + htmlBody + "</body></html>");
addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
// Process the click event on the link (for example with java.awt.Desktop.getDesktop().browse())
System.out.println(e.getURL()+" was clicked");
}
}
});
setEditable(false);
setBorder(null);
}
static StringBuffer getStyle() {
// for copying style
JLabel label = new JLabel();
Font font = label.getFont();
Color color = label.getBackground();
// create some css from the label's font
StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";");
style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";");
style.append("font-size:" + font.getSize() + "pt;");
style.append("background-color: rgb("+color.getRed()+","+color.getGreen()+","+color.getBlue()+");");
return style;
}
}
Usage:
JOptionPane.showMessageDialog(null, new MessageWithLink("Here is a link on <a href=\"http://www.google.com\">http://www.google.com</a>"));
You can add any component to a JOptionPane.
So add a JEditorPane which displays your HTML and supports a HyperlinkListener.