在Java Swing程序中,有时候需要在窗口显示一些HTML内容,其中有可能有一些超链接。例如:在显示软件版本信息时,给出作者email,以及软件主页,并希望用户点击这些链接时能直接打开。这时就需要使用HyperlinkListener了。
请 直接看示例代码,并注意注释中的提醒。
其中:Desktop.getDesktop().browse(linkUrl.toURI()); 是打开超链接的关键代码(JDK6适用)。
HyperlinkListener hlLsnr = new HyperlinkListener(){
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED)
return;
//超链接标记中必须带有协议指定,e.getURL()才能得到,否则只能用e.getDescription()得到href的内容。
// JOptionPane.showMessageDialog(InfoDialog.this, "URL:"+e.getURL()+"\nDesc:"+ e.getDescription());
URL linkUrl = e.getURL();
if (linkUrl!=null){
try {
Desktop.getDesktop().browse(linkUrl.toURI());
} catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(InfoDialog.this,"超链接错误","无法打开超链接:"+linkUrl
+"\n详情:"+e1,JOptionPane.ERROR_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(InfoDialog.this,"超链接错误","超链接信息不完整:"+e.getDescription()
+"\n请确保链接带有协议信息,如http://,mailto:",JOptionPane.ERROR_MESSAGE);
}
}
};
注意:超链接标记中必须带有协议指定,e.getURL()才能得到,否则只能用e.getDescription()得到href的内容。
应用:
TextPane txtInfo = new JTextPane();
txtInfo.addHyperlinkListener(hlLsnr);
txtInfo.setEditable(false);//没有这句,超链接无法激活!参考百度文章:http://hi.baidu.com/thelongesturl/item/479b740a4e2561df73e6768b