Swing JDialog / JTextPane and HTML Links

I am using an html page inside a JTextPane swing in JDialog.
In html, I have <a href="mailto: email@adress.com ">John</a>
When I browse a web page through Explorer, when the mouse follows the link, I see mailto .
When I click the link, I get the error message "The mail client is not installed by default," but I think this is due to the fact that I did not configure Outlook or any other program on my PC. When I open JDialog from my Swing application, I see John highlighted as a link, but when I click the link, nothing happens.
I expected to get the same error message as the browser.
So my question is, is it possible to open the link through the Swing app or not?

thanks

+4
source share
2 answers

Neither the tooltip (showing the address of the target hyperlink) nor the action when clicked occurs automatically, you must encode it: for the first register the panel using ToolTipManager, for the latter register the HyperlinkListener, something like:

  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); 

An example of opening a page in the same panel. If you want to activate the default browser / mail client, ask the Desktop (new for jdk1.6) to do it for you

+6
source
 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); 
0
source

All Articles