1 19 20 package org.openide.util; 21 22 import java.awt.Component ; 23 import java.awt.event.ActionEvent ; 24 import java.awt.event.ActionListener ; 25 import java.awt.event.HierarchyEvent ; 26 import java.awt.event.HierarchyListener ; 27 import javax.swing.SwingUtilities ; 28 import javax.swing.Timer ; 29 30 40 final class AsyncInitSupport implements HierarchyListener , Runnable , ActionListener { 41 42 private static final Object CANCELLED_LOCK = new Object (); 43 44 45 private Task initTask; 46 47 48 private boolean wasCancelled; 49 50 51 private Component comp4Init; 52 53 54 private AsyncGUIJob initJob; 55 56 57 Timer timer = null; 58 59 64 public AsyncInitSupport(Component comp4Init, AsyncGUIJob initJob) { 65 this.comp4Init = comp4Init; 66 this.initJob = initJob; 67 if (comp4Init.isShowing()) { 68 throw new IllegalStateException ("Component already shown, can't be inited: " + comp4Init); 69 } 70 71 comp4Init.addHierarchyListener(this); 72 } 73 74 79 public void hierarchyChanged(HierarchyEvent evt) { 80 if (((evt.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0)) { 81 boolean isShowing = comp4Init.isShowing(); 82 if (timer == null && isShowing) { 83 timer = new Timer (20, this); 84 timer.setRepeats(false); 85 timer.start(); 86 } else if (!isShowing) { 87 comp4Init.removeHierarchyListener(this); 88 cancel(); 89 } 90 } 91 } 92 93 95 public void actionPerformed(ActionEvent ae) { 96 if (wasCancelled || (initTask != null)) { 97 detach(); 99 return; 100 } 101 102 if ((comp4Init != null) && comp4Init.isDisplayable()) { 103 start(); 105 } 106 } 107 108 private void start() { 109 detach(); 110 111 if (initTask == null) { 112 initTask = RequestProcessor.getDefault().post(this); 113 } 114 } 115 116 private void detach() { 117 if (timer != null) { 118 timer.stop(); 119 } 120 } 121 122 126 public void run() { 127 if (!SwingUtilities.isEventDispatchThread()) { 128 initJob.construct(); 130 comp4Init.removeHierarchyListener(this); 131 132 boolean localCancel; 134 135 synchronized (CANCELLED_LOCK) { 136 localCancel = wasCancelled; 137 } 138 139 if (!localCancel) { 140 SwingUtilities.invokeLater(this); 141 } 142 } else { 143 initJob.finished(); 145 } 146 } 147 148 150 private void cancel() { 151 if ((initTask != null) && !initTask.isFinished() && (initJob instanceof Cancellable)) { 152 synchronized (CANCELLED_LOCK) { 153 wasCancelled = true; 154 } 155 ((Cancellable) initJob).cancel(); 156 } 157 } 158 159 } 160 | Popular Tags |