web-dev-qa-db-fra.com

Obtenir Java gui pour ouvrir une page Web dans un navigateur Web

J'essaie d'obtenir un Java gui pour ouvrir une page Web. Donc, le gui exécute du code qui fait des choses et produit ensuite un fichier html. Je veux ensuite que ce fichier s'ouvre dans un navigateur Web (de préférence Firefox) dès sa création, comment faire?

34
The Special One

Si vous utilisez Java 6 ou supérieur, voir l'API Desktop , en particulier parcourir . Utilisez-le comme ceci (non testé) :

// 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);
39
Dan Vinton

Oui, mais si vous voulez ouvrir la page Web dans votre navigateur Web par défaut par un programme Java alors vous pouvez essayer d'utiliser ce code.

/// 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
27
Ankur

Je sais que toutes ces réponses ont essentiellement répondu à la question, mais voici le code d'une méthode qui échoue gracieusement.

Notez que la chaîne peut être l'emplacement d'un fichier 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 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);
        }
}
2
Troyseph

J'ai utilisé BrowserLauncher2 avec succès. Il invoquera le navigateur par défaut sur toutes les plates-formes testées. Je l'utilise pour la démonstration de logiciels via JNLP. Le logiciel télécharge, exécute et dirige le navigateur de l'utilisateur vers des pages d'informations/commentaires, etc.

JDK 1.4 et supérieur, je crois.

0
Brian Agnew