Search code examples
javamacosswingjoptionpanejeditorpane

Hyperlink in JEditorPane not opening on MAC


I have a JEditorPane, showing in a JOptionPane, with an URL I want to open before closing my application. It works well on Windows and Linux, but it doesn't work on Mac.

Here is the code :

//LINK
String link = "http://www.google.com/";
String link_name = "Google";

//Editor_Pane
JEditorPane editor_pane = new JEditorPane();
editor_pane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editor_pane.setText( /*some text*/  + "<a href=\"" + link + "\">" + link_name + "</a>");
editor_pane.setEditable(false);

//ADD A LISTENER
editor_pane.addHyperlinkListener(new HyperlinkListener(){
    public void hyperlinkUpdate(HyperlinkEvent e){
        if(e.getEventType() == (HyperlinkEvent.EventType.ACTIVATED)){

            //OPEN THE LINK
            try{ Desktop.getDesktop().browse(e.getURL().toURI());
            }catch (IOException | URISyntaxException e1) {e1.printStackTrace();}

            //EXIT
            System.exit(0);
        }
    }
});

//SHOW THE PANE
JOptionPane.showOptionDialog(null, editor_pane, "text", JOptionPane.DEFAULT_OPTION, 
                             JOptionPane.PLAIN_MESSAGE, null, new Object[] {}, null);

The link seems clickable, but nothing happens when I click, even if I try to remove the Desktop.browse method and let only the exit method.

What am I doing wrong ? Thanks !


Solution

  • Try adding:

    editor_pane.setEditable(false);
    

    The pane needs to be readonly for links to be clickable. See JEditorPane for more details:

    The HTML EditorKit will generate hyperlink events if the JEditorPane is not editable (JEditorPane.setEditable(false); has been called).

    EDIT:

    import java.awt.Cursor;
    import java.awt.Desktop;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.net.URI;
    
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    
    public class TestLink {
    
        public static void main(String[] args) {
            JLabel label = new JLabel("stackoverflow");
            label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    
            label.addMouseListener(new MouseAdapter() {  
                public void mouseClicked(MouseEvent e) {  
                    if (Desktop.isDesktopSupported()) {
                        try {
                          Desktop.getDesktop().browse(new URI("http://stackoverflow.com"));
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                      } else { 
                          //TODO 
                      }
                }  
            }); 
            JOptionPane.showMessageDialog(null, label);
        }
    }