用java按钮在浏览器中打开一个链接?

Mal*_*e94 101 java browser desktop swing hyperlink

如何通过单击按钮在默认浏览器中打开链接

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

FTh*_*son 221

使用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;
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 36

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


小智 26

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

注意:您必须包含必要的导入 java.net


kop*_*por 5

没有桌面环境的解决方案是BrowserLauncher2.这个解决方案比Linux更通用,桌面并不总是可用.

长篇答案发布在/sf/answers/1517340331/