使用 java 按钮在浏览器中打开链接? [英] Open a link in browser with java button?

查看:35
本文介绍了使用 java 按钮在浏览器中打开链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

?

推荐答案

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

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

这篇关于使用 java 按钮在浏览器中打开链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆