Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

java - 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))
                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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can add any component to a JOptionPane.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...