Getting java gui to open a webpage in web browser

后端 未结 4 1569
野的像风
野的像风 2020-11-28 10:20

I am trying to get a java gui to open a web page. So the gui runs some code that does things and then produces a html file. I then want this file to open in a web browser (p

4条回答
  •  盖世英雄少女心
    2020-11-28 10:49

    I know that all of these answers have basically answered the question, but here is a the code for a method that fails gracefully.

    Note that the string can be the location of an html file

    /**
    * 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 e.t.c 
    */
    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);
            }
    }
    

提交回复
热议问题