Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class Main {
    /**
     * Adds a hand cursor to the component, as well as a click listener that
     * triggers a browse action to the given url.
     */
    public static void addBrowseBehavior(final Component cmp, final String url) {
        if (url == null)
            return;
        cmp.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        cmp.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JFrame frame = getJFrame(cmp);
                browse(url, frame);
            }
        });
    }

    /**
     * Gets the parent JFrame of the component.
     */
    public static JFrame getJFrame(Component cmp) {
        return (JFrame) SwingUtilities.getWindowAncestor(cmp);
    }

    /**
     * Opens the given website in the default browser, or shows a message saying
     * that no default browser could be accessed.
     */
    public static void browse(String url, Component msgParent) {
        boolean error = false;

        if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Action.BROWSE)) {
            try {
                Desktop.getDesktop().browse(new URI(url));
            } catch (URISyntaxException ex) {
                throw new RuntimeException(ex);
            } catch (IOException ex) {
                error = true;
            }
        } else {
            error = true;
        }

        if (error) {
            String msg = "Impossible to open the default browser from the application.\nSorry.";
            JOptionPane.showMessageDialog(msgParent, msg);
        }
    }
}