Search code examples
javaswinghyperlinktextareamailto

How to add lines to a textarea which contains mailto links in java?


I need to add lines to the textarea in swing which contains the mailto links and clicking on it should open email application.

How can I do it?


Solution

  • As I have suggested in my comment You should try JTextPane instead of JTextArea.

    In order to make hyper link work you need to do following things:

    • make textPane editable = false.
    • add a HyperlinkListener to it so that you can monitor link activate event.

    A quick demo is as follows:

        final JTextPane textPane = new JTextPane();
        textPane.setEditable(false);
        textPane.setContentType("text/html");
        textPane.setText("File not found please contact:<a href='mailto:[email protected]'>e-mail to</a> or call 9639");
        textPane.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(HyperlinkEvent e) {
                if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                    System.out.println(e.getURL());
                    // write your logic here to process mailTo link.
                }
            }
        });
    

    Example of opening mail client through java:

    try {
        Desktop.getDesktop().mail(new URI(e.getURL() + ""));
    } catch (IOException e1) {
        e1.printStackTrace();
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }