clickable links in JOptionPane

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 I have included an <a href> link. The link shows up blue and underlined in the dialog, however it is not clickable.

For example, this should also work:

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

How do I get clickable links within a JOptionPane?

Thanks, Paul.

EDIT - eg solution

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

Answers


You can add any component to a JOptionPane.

So add a JEditorPane which displays your HTML and supports a HyperlinkListener.


Need Your Help

how to know the path of the webcontainer using java?

java file jsp servlets path

I need to get the web container path using java, is there any method for that? I need to use it using JSP or Servlet to get a file path.

onDateSet does not get called from DatePickerDialog on tablet

java android tabs galaxy datepickerdialog

I am using a DatePickerDialog to prompt the user for a date. It works fine in the simulator and on my Samsung Galaxy Nexus, but onDateSet does not get called on my Samsung Galaxy Tab 2.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.