0

I imported an HTML file to be displayed in a JEditorPane, and in the HTML code are links. In the application however, the links wont open anything when clicked. The HTML page is displaying great, but those links wont work with me. Do they become disabled in the JEditorPane? And how do I get them to open to the linked website when clicked?

static JPanel createResourcesPage() {
    finalResourcesPage = new JPanel(new BorderLayout());

    JEditorPane editorpane = new JEditorPane();

    File file = new File("src/resourcesPageHTML.html");
    try {
        editorpane.setPage(file.toURI().toURL());
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    editorpane.setEditable(false);

    JScrollPane scroll = new JScrollPane(editorpane);
    scroll.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scroll.setPreferredSize(new Dimension(500, 300));

    finalResourcesPage.add(scroll);
    finalResourcesPage.add(editorpane);

    return finalResourcesPage;
}

EDIT: Forgot to include that the HTML file doesn't contain only links. It's just that there are links in the file.

Kev
  • 33
  • 2
  • 6

1 Answers1

0

Try something like this:

final JEditorPane links = new JEditorPane();
editor.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editor.setEditable(false);

Now you have to set the editor to the link text, and then add the click handler to it:

links.setText("<a href=\"http://www.google.com</a>");

links.addHyperlinkListener(new HyperlinkListener() {
    public void hyperlinkUpdate(HyperlinkEvent e) {
        if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
           // desired action for link
        }
    }
});

Now you can designate what happens when you click on the link. If you want to launch the default browser use this:

if(Desktop.isDesktopSupported()) 
{
Desktop.getDesktop().browse(e.getURL().toURI()); 
}
beastlyCoder
  • 2,349
  • 4
  • 25
  • 52
  • I just edited my post to say that the HTML file contains regular text as well. Does this make a difference to what you suggested? – Kev Nov 26 '18 at 22:36
  • I don't think it would matter, considering that the only text that would be activated by the listener were hyperlinks. – beastlyCoder Nov 26 '18 at 23:04