javaswingjeditorpanetel

Open telephone number link


I want to open MS Teams to dial a number like on a HTML webpage with the <a href="tel:..... tag. As far as I know, the HTML Version in Java is very old and maybe tel: is not supported in the included version. However, I tried this code which is working fine for normal HMTL links.

String st = "<html>\r\n<a href=\"tel:+4917312345678\">0173 12345678</a>\r\n</html>";
editorPane = new JEditorPane("text/html", st);
// handle link events
editorPane.addHyperlinkListener(new HyperlinkListener() {
    @Override
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED))
                try {
                    Desktop.getDesktop().browse(e.getURL().toURI());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (URISyntaxException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } // roll your own link launcher or use Desktop if J6+
    }
});
editorPane.setEditable(false);
editorPane.setBounds(72, 244, 423, 137);
panel_3.add(editorPane);

but this doesn't work for tel: links

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toURI()" because the return value of "javax.swing.event.HyperlinkEvent.getURL()" is null

Any ideas?


Solution

  • OK I found a way how I can use tel: links. My Code is only for windows so if you want to use if cross platform you have to do a check before like here

        String st = "<html>\r\n<a href=\"tel:+4917312345678\">+4917312345678</a>\r\n</html>";
        editorPane = new JEditorPane("text/html", st);
        // handle link events
        editorPane.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(HyperlinkEvent e) {
                if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED))
                        try {
                            Runtime rt = Runtime.getRuntime();
                            String url = e.getDescription();
                            System.out.println(url);
                            rt.exec("rundll32 url.dll,FileProtocolHandler " + url);
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
            }
        });
        editorPane.setEditable(false);
        editorPane.setBounds(72, 244, 423, 137);
        panel_3.add(editorPane);