【问题标题】:Open a link in browser with java button? [duplicate]用java按钮在浏览器中打开一个链接? [复制]
【发布时间】:2012-06-13 14:40:08
【问题描述】:

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

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

?

【问题讨论】:

标签: java swing browser hyperlink desktop


【解决方案1】:

使用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 调试并验证桌面是否受支持,并且安全实施不会限制您访问桌面实例。如果您将 JAR 作为小程序运行,安全性可能是罪魁祸首。
  • @Vulcan--我没有将 JAR 作为小程序运行。我不知道有任何安全设置会阻止它工作。我通过调用new ProcessBuilder("x-www-browser", uri.toString()); 来“解决”它。您会认为如果存在安全限制,ProcessBuilder 调用将不起作用。但它确实有效。我不知道为什么desktop.browse(uri) 不起作用,但我看到它对很多人不起作用。我猜这可能是 Netbeans 的问题,但我不知道。
  • 如果用户已经为文件扩展分配了一个自定义的“打开方式”操作,比如“html”,那么这将不会打开浏览器,但是用户已经将它链接到的程序......这个根本不是解决方案!
  • @thesaint 好点;另一种openWebpage 可以使用Runtime.exec(..) 并遍历一组预定义的流行浏览器名称,将URL 传递给它们。但是,这也有一个警告,即不为使用晦涩的浏览器的用户运行,但是当我有空闲时间时,我会尽快将其写入并添加到此答案中。
【解决方案2】:
public static void openWebpage(String urlString) {
    try {
        Desktop.getDesktop().browse(new URL(urlString).toURI());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【讨论】:

    【解决方案3】:
    try {
        Desktop.getDesktop().browse(new URL("http://www.google.com").toURI());
    } catch (Exception e) {}
    

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

    【讨论】:

      【解决方案4】:

      没有桌面环境的解决方案是BrowserLauncher2。此解决方案更通用,因为在 Linux 上,桌面并不总是可用。

      冗长的答案发布在https://stackoverflow.com/a/21676290/873282

      【讨论】:

        【解决方案5】:
        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());
            }
        }
        

        【讨论】:

        • 效果很好!谢谢
        【解决方案6】:

        我知道这是一个老问题,但有时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?
            }
        });
        

        【讨论】:

          【解决方案7】:
          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);
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-02-21
            • 2012-12-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多