1 7 package javax.swing; 8 9 import java.beans.PropertyChangeEvent ; 10 import java.beans.PropertyChangeListener ; 11 import java.io.*; 12 import java.lang.ref.WeakReference ; 13 import java.lang.ref.ReferenceQueue ; 14 15 36 abstract class ActionPropertyChangeListener<T extends JComponent > 37 implements PropertyChangeListener , Serializable { 38 private static ReferenceQueue <JComponent > queue; 39 40 private transient OwnedWeakReference<T> target; 42 private Action action; 45 46 private static ReferenceQueue <JComponent > getQueue() { 47 synchronized(ActionPropertyChangeListener .class) { 48 if (queue == null) { 49 queue = new ReferenceQueue <JComponent >(); 50 } 51 } 52 return queue; 53 } 54 55 public ActionPropertyChangeListener(T c, Action a) { 56 super(); 57 setTarget(c); 58 this.action = a; 59 } 60 61 66 public final void propertyChange(PropertyChangeEvent e) { 67 T target = getTarget(); 68 if (target == null) { 69 getAction().removePropertyChangeListener(this); 70 } else { 71 actionPropertyChanged(target, getAction(), e); 72 } 73 } 74 75 79 protected abstract void actionPropertyChanged(T target, Action action, 80 PropertyChangeEvent e); 81 82 private void setTarget(T c) { 83 ReferenceQueue <JComponent > queue = getQueue(); 84 OwnedWeakReference r; 88 while ((r = (OwnedWeakReference)queue.poll()) != null) { 89 ActionPropertyChangeListener oldPCL = r.getOwner(); 90 Action oldAction = oldPCL.getAction(); 91 if (oldAction!=null) { 92 oldAction.removePropertyChangeListener(oldPCL); 93 } 94 } 95 this.target = new OwnedWeakReference<T>(c, queue, this); 96 } 97 98 public T getTarget() { 99 if (target == null) { 100 return null; 102 } 103 return this.target.get(); 104 } 105 106 public Action getAction() { 107 return action; 108 } 109 110 private void writeObject(ObjectOutputStream s) throws IOException { 111 s.defaultWriteObject(); 112 s.writeObject(getTarget()); 113 } 114 115 @SuppressWarnings ("unchecked") 116 private void readObject(ObjectInputStream s) 117 throws IOException, ClassNotFoundException { 118 s.defaultReadObject(); 119 T target = (T)s.readObject(); 120 if (target != null) { 121 setTarget(target); 122 } 123 } 124 125 126 private static class OwnedWeakReference<U extends JComponent > extends 127 WeakReference <U> { 128 private ActionPropertyChangeListener owner; 129 130 OwnedWeakReference(U target, ReferenceQueue <? super U> queue, 131 ActionPropertyChangeListener owner) { 132 super(target, queue); 133 this.owner = owner; 134 } 135 136 public ActionPropertyChangeListener getOwner() { 137 return owner; 138 } 139 } 140 } 141 | Popular Tags |