Подтвердить что ты не робот

Получение java gui для открытия веб-страницы в веб-браузере

Я пытаюсь получить java gui, чтобы открыть веб-страницу. Таким образом, gui запускает некоторый код, который делает что-то, а затем создает html файл. Затем я хочу, чтобы этот файл открывался в веб-браузере (предпочтительно Firefox) сразу после его создания. Как мне это сделать?

4b9b3361

Ответ 1

Если вы используете Java 6 или выше, см. API Desktop, в частности browse. Используйте его так (не тестировалось):

// 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);

Ответ 2

Ya, но если вы хотите открыть веб-страницу в своем веб-браузере по умолчанию с помощью 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

Ответ 3

Я знаю, что все эти ответы в основном отвечали на вопрос, но вот код для метода, который изящно выходит из строя.

Обратите внимание, что строка может быть расположением html файла

/**
* If possible this method opens the default browser to the specified web page.
* If not it notifies the user of webpage 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);
        }
}

Ответ 4

Я использовал BrowserLauncher2 с успехом. Он будет вызывать браузер по умолчанию на всех тестируемых платформах. Я использую это для демонстрации программного обеспечения через JNLP. Программное обеспечение загружает, запускает и управляет браузером пользователя на информационных страницах/обратной связи и т.д.

JDK 1.4 и выше, я считаю.