[java] Open a link in browser with java button?

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

?

This question is related to java swing browser hyperlink desktop

The answer is


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

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

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


try {
    Desktop.getDesktop().browse(new URL("http://www.google.com").toURI());
} catch (Exception e) {}

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


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

public static void openWebpage(String urlString) {
    try {
        Desktop.getDesktop().browse(new URL(urlString).toURI());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to swing

Calling another method java GUI Read input from a JOptionPane.showInputDialog box Call japplet from jframe Java JTable getting the data of the selected row What does .pack() do? How to add row of data to Jtable from values received from jtextfield and comboboxes How can I check that JButton is pressed? If the isEnable() is not work? Load arrayList data into JTable How to draw a circle with given X and Y coordinates as the middle spot of the circle? Simplest way to set image as JPanel background

Examples related to browser

How to force reloading a page when using browser back button? How do we download a blob url video How to prevent a browser from storing passwords How to Identify Microsoft Edge browser via CSS? Edit and replay XHR chrome/firefox etc? Communication between tabs or windows How do I render a Word document (.doc, .docx) in the browser using JavaScript? "Proxy server connection failed" in google chrome Chrome - ERR_CACHE_MISS How to check View Source in Mobile Browsers (Both Android && Feature Phone) Wrapping a react-router Link in an html button How to make a hyperlink in telegram without using bots? React onClick and preventDefault() link refresh/redirect? How to put a link on a button with bootstrap? How link to any local file with markdown syntax? link with target="_blank" does not open in new tab in Chrome How to create a link to another PHP page How to determine the current language of a wordpress page when using polylang? How to change link color (Bootstrap) How can I make a clickable link in an NSAttributedString?

Examples related to desktop

How to center a component in Material-UI and make it responsive? Open a link in browser with java button? How to run a shell script in OS X by double-clicking? Which icon sizes should my Windows application's icon include? Chrome desktop notification example What's the environment variable for the path to the desktop? Good Free Alternative To MS Access