我正在使用JOptionPane來顯示一些產品信息,並需要添加一些鏈接到網頁。JOptionPane中的可點擊鏈接
我已經知道你可以使用包含html的JLabel,所以我包含了一個<a href>
鏈接。該鏈接在對話框中顯示爲藍色並加下劃線,但不可點擊。
例如,這也應該工作:
public static void main(String[] args) throws Throwable
{
JOptionPane.showMessageDialog(null, "<html><a href=\"http://google.com/\">a link</a></html>");
}
我如何獲得的JOptionPane內可點擊的鏈接?
謝謝,保羅。
編輯 - 例如解決方案
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);
}
的解決方案張貼我無法找到類ProcessHandler。它從何而來? – alexandre1985