Search code examples
javajoptionpane

Clickable links from ArrayList in JOptionPane


I'm trying to implement a history-button in my Browser class (created in eclipse), and I want the links in the button to be clickable. Here is my code that gets initiated when the user presses the button History:

private void showMessage() {
    try {
        String message = new String();
        message = history.toString();
        JOptionPane.showMessageDialog(null, message);
    } catch (NullPointerException e) {
        System.out.println("Something is wrong with your historylist!");
    }
}

In the code above, history is a list with all the webpages that has been previously visited.

I have tried using the method presented here: clickable links in JOptionPane, and I got it to work. The problem is, this solution only lets me predefine URL:s, but I want my list history to be displayed, and the URLs in it to be clickable.

For example, if I have visited https://www.google.com and https://www.engadget.com, the list will look like this: history = [www.google.com, www.engadget.com], and both links should be separately clickable.


Solution

  • This is the function that should be called when someone presses the history-button. It uses a JEditorPane with a HyperlinkListener. The string html in the code below adds the needed html-coding so that the HyperlinkListener can read and visit the webpages.

    public void historyAction() {
        String html = new String();
        for (String link : history) {
            html = html + "<a href=\"" + link + "\">" + link + "</a>\n";
        }
        html = "<html><body" + html + "</body></html>";
        JEditorPane ep = new JEditorPane("text/html", html);
        ep.addHyperlinkListener(new HyperlinkListener() {
            public void hyperlinkUpdate(HyperlinkEvent e) {
                if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
                    loadURL(e.getURL().toString());
                }
            }
        });
        ep.setEditable(false);
        JOptionPane.showMessageDialog(null, ep);
    }