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); }
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.
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.
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.
You can add any component to a JOptionPane.
So add a JEditorPane which displays your HTML and supports a HyperlinkListener.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With