anklickbare Links in JOptionPane

Ich bin mit einem JOptionPane angezeigt einige Produkt-Informationen und hinzufügen einige links zu web-Seiten.

Habe ich herausgefunden, dass man kann ein JLabel mit html, also habe ich noch ein <a href> link. Der link zeigt bis blau und Unterstrichen in den dialog, aber es ist nicht anklickbar.

Zum Beispiel, dies sollte auch funktionieren:

public static void main(String[] args) throws Throwable
{
    JOptionPane.showMessageDialog(null, "<html><a href=\"http://google.com/\">a link</a></html>");
}

Wie bekomme ich anklickbare links in einen JOptionPane?

Dank, Paul.

BEARBEITEN - eg-Lösung

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'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;");

    //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);
}

InformationsquelleAutor der Frage pstanton | 2011-12-01

Schreibe einen Kommentar