JOptionPane中的可点击链接 [英] clickable links in JOptionPane
问题描述
我正在使用JOptionPane显示一些产品信息,需要添加一些链接到网页。
I'm using a JOptionPane to display some product information and need to add some links to web pages.
我发现你可以使用JLabel包含html,所以我添加了< a href>
链接。该对话框中的链接显示为蓝色和带下划线,但不可点击。
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.
例如,这也应该有效:
public static void main(String[] args) throws Throwable
{
JOptionPane.showMessageDialog(null, "<html><a href=\"http://google.com/\">a link</a></html>");
}
如何在JOptionPane中获得可点击链接?
How do I get clickable links within a JOptionPane?
谢谢,保罗。
编辑 - 例如解决方案
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);
}
推荐答案
您可以添加任何组件到一个JOptionPane。
You can add any component to a JOptionPane.
所以添加一个JEditorPane,它显示你的HTML并支持HyperlinkListener。
So add a JEditorPane which displays your HTML and supports a HyperlinkListener.
这篇关于JOptionPane中的可点击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!