1

For the "About" dialog of my application, I have a JLabel which I have defined using html tag as follows:

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!).

How to do that?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user1639485
  • 808
  • 3
  • 14
  • 26

3 Answers3

3

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. Best to steer clear of attempting to parse the HTML.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

Unfortunately, HTML links within a JLabel are not "clickable" by default. Please, see this topic: How to add hyperlink in JLabel. It contains everything you may need to know about this topic.

Community
  • 1
  • 1
gd1
  • 11,300
  • 7
  • 49
  • 88
  • I found an example which uses Desktop.getDesktop().mail(...) Believe it should do my purpose. However, do I need to get the external jar for "java.awt.Desktop" as I am not able to import the same so as to use the mail() api. – user1639485 Sep 16 '12 at 18:59
  • 1
    *java.awt* is part of the core API so it doesn't any special Jars. Check which version of Java you are using. The Desktop API was only added in Java 6 – MadProgrammer Sep 16 '12 at 20:46
1

Or if you do not mind using an extra library, you can consider using the JXHyperLink from the SwingX project

Robin
  • 36,233
  • 5
  • 47
  • 99