Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clickable links in JOptionPane

Tags:

java

swing

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))                 Desktop.getDesktop().browse(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); } 
like image 817
pstanton Avatar asked Dec 01 '11 20:12

pstanton


People also ask

What is JOptionPane showMessageDialog?

It is used to create an information-message dialog titled "Message". static void showMessageDialog(Component parentComponent, Object message, String title, int messageType) It is used to create a message dialog with given title and messageType.

What is JOptionPane input dialog?

A dialog box is a small graphical window that displays a message to the user or requests input. Two of the dialog boxes are: – Message Dialog - a dialog box that displays a message. Input Dialog - a dialog box that prompts the user for input. The 'javax.swing.JOptionPane' class offers dialog box methods.

What should I import into JOptionPane?

The JOptionPane class is a part of the javax. swing package, so you need to add this import javax. swing. JOption Pane statement to the beginning of any proram that uses this class.


1 Answers

You can add any component to a JOptionPane.

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

like image 165
camickr Avatar answered Sep 28 '22 08:09

camickr