add Browse Behavior to Swing Application - Java Swing

Java examples for Swing:Swing HTML

Description

add Browse Behavior to Swing Application

Demo Code


//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 {
    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/*from   w ww. ja va2 s .c o m*/
            public void mousePressed(MouseEvent e) {
                JFrame frame = getJFrame(cmp);
                browse(url, frame);
            }
        });
    }

    public static JFrame getJFrame(Component cmp) {
        return (JFrame) SwingUtilities.getWindowAncestor(cmp);
    }

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

Related Tutorials