简体   繁体   中英

open web page from jframe

hello, is there a way to open a web page in the browser from jframe that contains a button or label

so when the user clicks the button or label the web page will open

hint: the button or label will be generated at run time

Look at the Desktop API . You do something like:

        try {
            Desktop.getDesktop().browse(new URI("http://www.google.com"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

This method fails gracefully, ie if the page doesn't open it alerts the user and helps them open it manually:

     /**
     * 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
     *            - the URL of the webpage which you wish to be opened.
     */
    public static void openWebpage(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);
                }
            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);
                }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM