问题

如何在按钮单击的情况下打开默认浏览器中的链接

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


#1 热门回答(208 赞)

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

#2 热门回答(32 赞)

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

#3 热门回答(22 赞)

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

注意:你必须包含java.net的必要进口商品


原文链接