1 6 21 22 package de.schlichtherle.key.passwd.swing; 23 24 import java.awt.*; 25 import java.beans.*; 26 import java.lang.ref.*; 27 28 import javax.swing.*; 29 30 37 final class WindowUtils { 38 private static final String PROPERTY_FOCUSED_WINDOW = "focusedWindow"; 39 40 private static Reference lastFocusManager = new WeakReference(null); 41 private static Reference lastFocusedWindow = lastFocusManager; 42 private static Reference parent; 43 44 private static PropertyChangeListener focusListener 45 = new PropertyChangeListener() { 46 public void propertyChange(PropertyChangeEvent evt) { 47 Window w = (Window) evt.getNewValue(); 48 if (w != null) 49 lastFocusedWindow = new WeakReference(w); 50 } 51 }; 52 53 57 private WindowUtils() { 58 } 59 60 63 public static synchronized Window getParentWindow() { 64 Window w = parent != null ? (Window) parent.get() : null; 65 if (w == null) { 66 w = WindowUtils.getLastFocusedWindow(); 67 if (w == null) 68 w = getAnyShowingWindow(); 69 } 70 71 for (Container c = w; c != null; c = c.getParent()) 74 if (c instanceof Window && c.isShowing()) 75 return (Window) c; 76 77 return JOptionPane.getRootFrame(); 79 } 80 81 84 public static synchronized void setParentWindow(Window w) { 85 parent = w != null ? new WeakReference(w) : null; 86 } 87 88 98 public static Window getLastFocusedWindow() { 99 observeFocusedWindow(); 100 return (Window) lastFocusedWindow.get(); 101 } 102 103 107 private static synchronized void observeFocusedWindow() { 108 final KeyboardFocusManager lfm 109 = (KeyboardFocusManager) lastFocusManager.get(); 110 final KeyboardFocusManager fm 111 = KeyboardFocusManager.getCurrentKeyboardFocusManager(); 112 if (fm == lfm) 113 return; 114 115 if (lfm != null) 116 lfm.removePropertyChangeListener( 117 PROPERTY_FOCUSED_WINDOW, focusListener); 118 fm.addPropertyChangeListener( 119 PROPERTY_FOCUSED_WINDOW, focusListener); 120 lastFocusManager = new WeakReference(fm); 121 lastFocusedWindow = new WeakReference(fm.getFocusedWindow()); 122 } 123 124 private static final Window getAnyShowingWindow() { 125 return getAnyShowingWindow(Frame.getFrames()); 126 } 127 128 private static Window getAnyShowingWindow(final Window[] windows) { 129 for (int i = 0, l = windows.length; i < l; i++) { 130 Window window = windows[i]; 131 if (window.isShowing()) 132 return window; 133 134 window = getAnyShowingWindow(window.getOwnedWindows()); 135 if (window != null) 136 return window; 137 } 138 139 return null; 140 } 141 } 142 | Popular Tags |