[英]Swing JDialog/JTextPane and HTML links
我在JDialog中的swing JTextPane
中使用了一个html页面。
在html中我有一个<a href="mailto:email@adress.com">John</a>
当我通过浏览器查看网页时,当鼠标转到链接时,我可以看到mailto
。
当我按下链接时,我收到错误“没有安装默认邮件客户端”,但我想这是由于在我的电脑中我没有配置Outlook或其他程序。
当我从Swing应用程序打开JDialog时,我看到John
突出显示为链接,但是当我按下链接时没有任何反应。
我希望得到与浏览器相同的错误消息。
所以我的问题是可以通过Swing应用程序打开链接吗?
谢谢
工具提示(显示目标超链接地址)和按下操作都不会自动发生,您必须对其进行编码:对于第一个,使用ToolTipManager注册窗格,对于后者,注册HyperlinkListener,如下所示:
final JEditorPane pane = new JEditorPane("http://swingx.java.net");
pane.setEditable(false);
ToolTipManager.sharedInstance().registerComponent(pane);
HyperlinkListener l = new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (HyperlinkEvent.EventType.ACTIVATED == e.getEventType()) {
try {
pane.setPage(e.getURL());
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
};
pane.addHyperlinkListener(l);
该示例是关于在同一窗格中打开页面。 如果要激活默认浏览器/邮件客户端,请询问桌面(jdk1.6的新用户)为您执行此操作
final JEditorPane jep = new JEditorPane("text/html",
"The rain in <a href='http://foo.com/'>Spain</a> falls mainly on the <a href='http://bar.com/'>plain</a>.");
jep.setEditable(false);
jep.setOpaque(false);
final Desktop desktop = Desktop.getDesktop();
jep.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent hle) {
if (HyperlinkEvent.EventType.ACTIVATED.equals(hle.getEventType())) {
try {
System.out.println(hle.getURL());
jep.setPage(hle.getURL());
try {
desktop.browse(new URI(hle.getURL().toString()));
} catch (URISyntaxException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
JPanel p = new JPanel();
p.add(new JLabel("Foo."));
p.add(jep);
p.add(new JLabel("Bar."));
JFrame f = new JFrame("HyperlinkListener");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(p, BorderLayout.CENTER);
f.setSize(400, 150);
f.setVisible(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.