[英]clickable email address as a JLabel in java
For the "About" dialog of my application, I have a JLabel which I have defined using html tag as follows: 对于我的应用程序的“关于”对话框,我有一个JLabel,它是使用html标记定义的,如下所示:
JLabel myEmail = new JLabel(
"<html><br><font size=2><a href=mailto:abc.pqr@xyz.com>abc.pqr@xyz.com</a>" +
"</font></html>");`
I want that on clicking this JLabel
, the default email client (say Outlook) gets opened with the To
field populated as abc.pqr@xyz.com
and subject
as a predefined text (say, Hi!
). 我希望单击此
JLabel
,将打开默认电子邮件客户端(例如Outlook),并将“ To
字段填充为abc.pqr@xyz.com
并以预定义的文本作为subject
(例如, Hi!
)。
How to do that? 怎么做?
Here is a snippet on how you could do this: 以下是有关如何执行此操作的摘要:
String address = "abc.pqr@xyz.com"; // global
JLabel label = new JLabel("<html><br><font size=2><a href=#>" + address + "</a></font></html>");
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().mail(new URI("mailto:" + address + "?subject=Hello"));
} catch (URISyntaxException | IOException ex) {
// ...
}
}
});
For demonstration purposes, the address
variable is global here but you should use a concrete MouseAdapter
subclass to pass in the associated email address. 出于演示目的,这里的
address
变量是全局变量,但是您应该使用具体的MouseAdapter
子类来传递关联的电子邮件地址。 Best to steer clear of attempting to parse the HTML. 最好避免尝试解析HTML。
Unfortunately, HTML links within a JLabel are not "clickable" by default. 不幸的是,默认情况下,JLabel中的HTML链接不可“单击”。 Please, see this topic: How to add hyperlink in JLabel .
请参阅此主题: 如何在JLabel中添加超链接 。 It contains everything you may need to know about this topic.
它包含您可能需要了解的有关此主题的所有信息。
或者,如果您不介意使用额外的库,则可以考虑使用SwingX项目中的JXHyperLink
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.