108

How can I open a link in default browser with a button click, along the lines of

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        open("www.google.com"); // just what is the 'open' method?
    }
});

?

Malasuerte94
  • 1,454
  • 3
  • 14
  • 18
  • 3
    You might have tried looking at the [JavaDocs for the class](http://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html) that is used in the accepted answer of your [last question](http://stackoverflow.com/questions/10966999/how-to-make-a-button-that-when-clicked-opens-the-appdata-directory)! Those docs. are very handy, either attach them to you IDE or bookmark the on-line version. – Andrew Thompson Jun 10 '12 at 10:08
  • Duplicate question: http://stackoverflow.com/q/5226212/873282 – koppor Jun 21 '15 at 12:05

7 Answers7

231

Use the Desktop#browse(URI) method. It opens a URI in the user's default browser.

public static boolean openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(uri);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

public static boolean openWebpage(URL url) {
    try {
        return openWebpage(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return false;
}
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • this doesn't appear to work in JAR files created by Netbeans 7.x. It works when the code is run from Netbeans, but not when deployed as a JAR file... at least in my experience. I'm still looking for a solution. – MountainX Feb 16 '14 at 18:43
  • @MountainX Debug and verify that the desktop is supported and that security implementations aren't restricting you from accessing the desktop instance. If you are running the JAR as an applet, security is the likely culprit. – FThompson Feb 18 '14 at 07:06
  • @Vulcan--I'm not running the JAR as an applet. I'm not aware of any security settings that would prevent this from working. I "worked around" it by calling `new ProcessBuilder("x-www-browser", uri.toString());`. You would think that if there were security restrictions, the ProcessBuilder call would not work. But it does work. I have no idea why `desktop.browse(uri)` doesn't work, but I have seen that it doesn't work for a lot of people. I was guessing maybe it's a Netbeans issue, but I don't know. – MountainX Feb 19 '14 at 01:51
  • If the user has assigned a custom "open with" action to the file exten like "html" then this will NOT open the browser, but the program the user has linked it with.... This is not a solution at all! – thesaint May 07 '15 at 20:11
  • @thesaint Great point; an alternative `openWebpage` could use `Runtime.exec(..)` and iterate through a pre-defined set of popular browser names, passing them the URL. That also has the caveat of not running for users with obscure browsers, however, but I'll write and add it to this answer soon when I have a free moment. – FThompson May 07 '15 at 23:53
  • Iterating over a pre-defined set of popular browsers will also not yield a desirable result for some users. They may have a default browser of Internet Explorer and our hypothetical program may place Chrome before IE in the list of browsers. The user may even have IE open and then wonder why Chrome is being used and not their default browser, IE. – Jason Mar 16 '20 at 14:27
39
public static void openWebpage(String urlString) {
    try {
        Desktop.getDesktop().browse(new URL(urlString).toURI());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Daniel Barral
  • 3,896
  • 2
  • 35
  • 47
25
try {
    Desktop.getDesktop().browse(new URL("http://www.google.com").toURI());
} catch (Exception e) {}

note: you have to include necessary imports from java.net

AdelM
  • 261
  • 3
  • 4
5

A solution without the Desktop environment is BrowserLauncher2. This solution is more general as on Linux, Desktop is not always available.

The lenghty answer is posted at https://stackoverflow.com/a/21676290/873282

Community
  • 1
  • 1
koppor
  • 19,079
  • 15
  • 119
  • 161
4
private void ButtonOpenWebActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        String url = "https://www.google.com";
        java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
    } catch (java.io.IOException e) {
        System.out.println(e.getMessage());
    }
}
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
1
public static void openWebPage(String url) {
    try {
        Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
        if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
            desktop.browse(new URI(url));
        }
        throw new NullPointerException();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, url, "", JOptionPane.PLAIN_MESSAGE);
    }
}
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
1

I know that this is an old question but sometimes the Desktop.getDesktop() produces an unexpected crash like in Ubuntu 18.04. Therefore, I have to re-write my code like this:

public static void openURL(String domain)
{
    String url = "https://" + domain;
    Runtime rt = Runtime.getRuntime();
    try {
        if (MUtils.isWindows()) {
            rt.exec("rundll32 url.dll,FileProtocolHandler " + url).waitFor();
            Debug.log("Browser: " + url);
        } else if (MUtils.isMac()) {
            String[] cmd = {"open", url};
            rt.exec(cmd).waitFor();
            Debug.log("Browser: " + url);
        } else if (MUtils.isUnix()) {
            String[] cmd = {"xdg-open", url};
            rt.exec(cmd).waitFor();
            Debug.log("Browser: " + url);
        } else {
            try {
                throw new IllegalStateException();
            } catch (IllegalStateException e1) {
                MUtils.alertMessage(Lang.get("desktop.not.supported"), MainPn.getMainPn());
                e1.printStackTrace();
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

public static boolean isWindows()
{
    return OS.contains("win");
}

public static boolean isMac()
{
    return OS.contains("mac");
}

public static boolean isUnix()
{
    return OS.contains("nix") || OS.contains("nux") || OS.indexOf("aix") > 0;
}

Then we can call this helper from the instance:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        MUtils.openURL("www.google.com"); // just what is the 'open' method?
    }
});
Teocci
  • 7,189
  • 1
  • 50
  • 48