1package aurelienribon.utils.swing;
2
3import java.awt.Component;
4import java.awt.Desktop;
5import java.awt.Desktop.Action;
6import java.awt.Dimension;
7import java.awt.Point;
8import java.awt.Window;
9import java.awt.event.HierarchyEvent;
10import java.awt.event.HierarchyListener;
11import java.awt.event.WindowListener;
12import java.io.IOException;
13import java.net.URI;
14import java.net.URISyntaxException;
15import javax.swing.JOptionPane;
16import javax.swing.SwingUtilities;
17
18/**
19 * @author Aurelien Ribon | http://www.aurelienribon.com
20 */
21public class SwingHelper {
22	/**
23	 * Adds a listener to the window parent of the given component. Can be
24	 * before the component is really added to its hierachy.
25	 * @param source The source component
26	 * @param listener The listener to add to the window
27	 */
28	public static void addWindowListener(final Component source, final WindowListener listener) {
29		if (source instanceof Window) {
30			((Window)source).addWindowListener(listener);
31		} else {
32			source.addHierarchyListener(new HierarchyListener() {
33				@Override public void hierarchyChanged(HierarchyEvent e) {
34					if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) == HierarchyEvent.SHOWING_CHANGED) {
35						SwingUtilities.getWindowAncestor(source).addWindowListener(listener);
36					}
37				}
38			});
39		}
40	}
41
42	/**
43	 * Centers a component according to the window location.
44	 * @param wnd The parent window
45	 * @param cmp A component, usually a dialog
46	 */
47	public static void centerInWindow(Window wnd, Component cmp) {
48		Dimension size = wnd.getSize();
49		Point loc = wnd.getLocationOnScreen();
50		Dimension cmpSize = cmp.getSize();
51		loc.x += (size.width  - cmpSize.width)/2;
52		loc.y += (size.height - cmpSize.height)/2;
53		cmp.setBounds(loc.x, loc.y, cmpSize.width, cmpSize.height);
54	}
55
56	/**
57	 * Opens the given website in the default browser, or show a message saying
58	 * that no default browser could be accessed.
59	 * @param parent The parent of the error message, if raised
60	 * @param uri The website uri
61	 */
62	public static void browse(Component parent, String uri) {
63		boolean cannotBrowse = false;
64		if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Action.BROWSE)) {
65			try {
66				Desktop.getDesktop().browse(new URI(uri));
67			} catch (URISyntaxException ex) {
68			} catch (IOException ex) {
69				cannotBrowse = true;
70			}
71		} else {
72			cannotBrowse = true;
73		}
74
75		if (cannotBrowse) {
76			JOptionPane.showMessageDialog(parent,
77				"It seems that I can't open a website using your"
78				+ "default browser, sorry.");
79		}
80	}
81}
82