Ответ 1
Вы можете добавить любой компонент в JOptionPane.
Итак, добавьте JEditorPane, который отображает ваш HTML и поддерживает HyperlinkListener.
Я использую JOptionPane для отображения информации о продукте и вам нужно добавить некоторые ссылки на веб-страницы.
Я понял, что вы можете использовать JLabel, содержащий html, поэтому я включил ссылку <a href>
. Ссылка отображается синим цветом и подчеркнута в диалоговом окне, однако она не может быть нажата.
Например, это также должно работать:
public static void main(String[] args) throws Throwable
{
JOptionPane.showMessageDialog(null, "<html><a href=\"http://google.com/\">a link</a></html>");
}
Как получить интерактивные ссылки в JOptionPane?
Спасибо, Пол.
EDIT - например, решение
public static void main(String[] args) throws Throwable
{
// for copying style
JLabel label = new JLabel();
Font font = label.getFont();
// create some css from the label font
StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";");
style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";");
style.append("font-size:" + font.getSize() + "pt;");
// html content
JEditorPane ep = new JEditorPane("text/html", "<html><body style=\"" + style + "\">" //
+ "some text, and <a href=\"http://google.com/\">a link</a>" //
+ "</body></html>");
// handle link events
ep.addHyperlinkListener(new HyperlinkListener()
{
@Override
public void hyperlinkUpdate(HyperlinkEvent e)
{
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED))
ProcessHandler.launchUrl(e.getURL().toString()); // roll your own link launcher or use Desktop if J6+
}
});
ep.setEditable(false);
ep.setBackground(label.getBackground());
// show
JOptionPane.showMessageDialog(null, ep);
}
Вы можете добавить любой компонент в JOptionPane.
Итак, добавьте JEditorPane, который отображает ваш HTML и поддерживает HyperlinkListener.
Похоже, это было подробно обсуждено здесь Как добавить гиперссылку в JLabel
Решение, предложенное ниже ответа, не работает с Nimbus Look and Feel. Нимбус переопределяет цвет фона и делает фон белым. Решение состоит в том, чтобы установить цвет фона в css. Вам также необходимо удалить границу компонента. Вот класс, который реализует решение, которое работает с нимбом (я не проверял другие 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 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;
}
}
Использование:
JOptionPane.showMessageDialog(null, new MessageWithLink("Here is a link on <a href=\"http://www.google.com\">http://www.google.com</a>"));