用Java按钮在浏览器中打开链接?

108

如何在按钮点击时使用默认浏览器打开链接,类似于:

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

?


3
你可能已经尝试查看上一个问题的 已接受答案 中使用的类的 JavaDoc。那些文档非常方便,可以将它们附加到你的集成开发环境中或将在线版本加为书签。 - Andrew Thompson
重复问题:https://dev59.com/lm435IYBdhLWcg3wxDBp - koppor
7个回答

232

使用Desktop#browse(URI) 方法,在用户的默认浏览器中打开一个URI。

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

这似乎在Netbeans 7.x创建的JAR文件中无法正常工作。当代码从Netbeans运行时,它可以工作,但是当部署为JAR文件时却不能...至少在我的经验中是如此。我仍在寻找解决方案。 - MountainX
请 @MountainX 进行调试和验证,确保桌面受到支持,并且安全实现不会限制您访问桌面实例。如果您将 JAR 作为小应用运行,则安全性很可能是罪魁祸首。 - FThompson
@Vulcan--我没有将JAR作为小程序运行。我不知道有什么安全设置会阻止它的工作。我通过调用new ProcessBuilder("x-www-browser", uri.toString());来“解决”这个问题。如果存在安全限制,你会认为ProcessBuilder调用不起作用。但它确实有效。我不知道为什么desktop.browse(uri)不起作用,但我已经看到很多人都遇到了这个问题。我猜可能是Netbeans的问题,但我不确定。 - MountainX
如果用户已经为文件扩展名(例如“html”)分配了自定义的“打开方式”操作,则不会打开浏览器,而是打开用户链接的程序... 这根本不是解决方案! - thesaint
@thesaint 很好的观点;另一种openWebpage的替代方法可以使用Runtime.exec(..)并迭代通过预定义的流行浏览器名称集合,将它们传递给URL。然而,这也有一个缺点,即不能为使用不常见浏览器的用户运行,但是当我有空闲时间时,我会编写并将其添加到此答案中。 - FThompson
迭代预定义的流行浏览器集合也不能为某些用户产生理想的结果。他们可能有一个默认的Internet Explorer浏览器,而我们假设的程序可能会在浏览器列表中将Chrome放在IE之前。用户甚至可能已经打开了IE,然后想知道为什么使用Chrome而不是他们的默认浏览器IE。 - Jason

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

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

注意:你需要从java.net中导入必要的引用。


5

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

它完美地运行了!谢谢。 - wilmerlpr

1

我知道这是一个老问题,但有时Desktop.getDesktop()会导致意外崩溃,比如在Ubuntu 18.04中。因此,我不得不像这样重新编写我的代码:

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

然后我们可以从实例中调用这个帮助程序:
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        MUtils.openURL("www.google.com"); // just what is the 'open' method?
    }
});

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接