1 package aurelienribon.utils.swing; 2 3 import java.awt.Component; 4 import java.awt.Desktop; 5 import java.awt.Desktop.Action; 6 import java.awt.Dimension; 7 import java.awt.Point; 8 import java.awt.Window; 9 import java.awt.event.HierarchyEvent; 10 import java.awt.event.HierarchyListener; 11 import java.awt.event.WindowListener; 12 import java.io.IOException; 13 import java.net.URI; 14 import java.net.URISyntaxException; 15 import javax.swing.JOptionPane; 16 import javax.swing.SwingUtilities; 17 18 /** 19 * @author Aurelien Ribon | http://www.aurelienribon.com 20 */ 21 public 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 */ addWindowListener(final Component source, final WindowListener listener)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 */ centerInWindow(Window wnd, Component cmp)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 */ browse(Component parent, String uri)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