让java gui在web浏览器中打开一个网页

我想获得一个Java GUI打开一个网页。 所以gui运行一些代码,然后生成一个html文件。 然后,我希望这个文件可以在网页浏览器(最好是Firefox)中创build。 我将如何去做呢?

如果您使用Java 6或更高版本,请参阅桌面 API,尤其是浏览 。 像这样使用它(未经testing):

// using this in real life, you'd probably want to check that the desktop // methods are supported using isDesktopSupported()... String htmlFilePath = "path/to/html/file.html"; // path to your new file File htmlFile = new File(htmlFilePath); // open the default web browser for the HTML page Desktop.getDesktop().browse(htmlFile.toURI()); // if a web browser is the default HTML handler, this might work too Desktop.getDesktop().open(htmlFile); 

雅,但如果你想打开你的默认网页浏览器的Java程序的网页,那么你可以尝试使用这个代码。

 /// file OpenPageInDefaultBrowser.java public class OpenPageInDefaultBrowser { public static void main(String[] args) { try { //Set your page url in this string. For eg, I m using URL for Google Search engine String url = "http://www.google.com"; java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); } catch (java.io.IOException e) { System.out.println(e.getMessage()); } } } /// End of file 

我知道所有这些答案都已经基本回答了这个问题,但是这里是一个方法的代码,不能正常地失败。

请注意,该string可以是一个HTML文件的位置

 /** * If possible this method opens the default browser to the specified web page. * If not it notifies the user of webpage's url so that they may access it * manually. * * @param url * - this can be in the form of a web address (http://www.mywebsite.com) * or a path to an html file or SVG image file etc */ public static void openInBrowser(String url) { try { URI uri = new URL(url).toURI(); Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { desktop.browse(uri); } else { throw new Exception("Desktop not supported, cannout open browser automatically"); } } catch (Exception e) { /* * I know this is bad practice * but we don't want to do anything clever for a specific error */ e.printStackTrace(); // Copy URL to the clipboard so the user can paste it into their browser StringSelection stringSelection = new StringSelection(url); Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); clpbrd.setContents(stringSelection, null); // Notify the user of the failure WindowTools.informationWindow("This program just tried to open a webpage." + "\n" + "The URL has been copied to your clipboard, simply paste into your browser to access.", "Webpage: " + url); } } 

我已经成功地使用了BrowserLauncher2 。 它会调用所有testing平台上的默认浏览器。 我使用这个通过JNLP演示软件。 该软件下载,运行和驱动用户的浏览器信息页面/反馈等。

JDK 1.4及以上,我相信。