Display given url in the default browser. - Java java.awt

Java examples for java.awt:Desktop

Description

Display given url in the default browser.

Demo Code


//package com.java2s;
import java.awt.Component;
import java.awt.Desktop;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import javax.swing.JOptionPane;

public class Main {
    /**/*from  w  ww. j  ava  2  s .co m*/
     * Display given <code>url</code> in the default browser. If this action is not supported
     * a message dialog with an error message is displayed.
     *
     * @param parent parent for error message dialog
     * @param url url to be displayed
     */
    public static void displayUrl(Component parent, String url) {
        try {
            Desktop.getDesktop().browse(URI.create(url));
        } catch (IOException | IllegalArgumentException
                | NullPointerException e) {
            e.printStackTrace();
            // TODO localize!
            JOptionPane.showMessageDialog(
                    parent,
                    "oops - could not show url ('" + url + "'): "
                            + e.toString(), "oops",
                    JOptionPane.ERROR_MESSAGE | JOptionPane.OK_OPTION);
        }
    }

    /**
     * Convenience method to display an url.
     *
     * @param parent component to display in
     * @param url URL to display
     * @see #displayUrl(Component, String)
     */
    public static void displayUrl(Component parent, URL url) {
        displayUrl(parent, url.toString());
    }
}

Related Tutorials