1 7 8 package org.jdesktop.dataset.provider; 9 10 import java.util.LinkedList ; 11 import javax.swing.Icon ; 12 import javax.swing.SwingUtilities ; 13 import org.jdesktop.dataset.DataTable; 14 15 16 20 public abstract class LoadTask extends AbstractTask { 21 31 private LinkedList loadQueue = new LinkedList (); 32 33 37 private LoadNotifier loadNotifier = new LoadNotifier(); 38 39 42 private DataTable[] tables; 43 44 48 public LoadTask(DataTable[] tables) { 49 this.tables = tables == null ? new DataTable[0] : tables; 50 } 51 52 55 public void run() { 56 setIndeterminate(true); 57 try { 58 readData(tables); 60 scheduleLoad(); 61 setProgress(getMaximum()); 62 } catch (Exception e) { 63 final Throwable error = e; 64 e.printStackTrace(); 65 setProgress(getMaximum()); 66 } 67 } 68 69 88 protected abstract void readData(final DataTable[] tables) throws Exception ; 89 90 116 protected abstract void loadData(LoadItem[] items); 117 118 130 protected void scheduleLoad(LoadItem item) { 131 synchronized (loadQueue) { 132 if (item != null) { 133 loadQueue.addLast(item); 134 } 135 if (!loadNotifier.isPending()) { 136 loadNotifier.setPending(true); 137 SwingUtilities.invokeLater(loadNotifier); 138 } 139 } 140 } 141 142 147 protected void scheduleLoad() { 148 scheduleLoad(null); 149 } 150 151 154 public String getDescription() { 155 return "<html><h3>Loading data</h3></html>"; 156 } 157 158 161 public Icon getIcon() { 162 return null; 163 } 164 165 168 public String getMessage() { 169 return "Loading item " + (getProgress() + 1) + " of " + getMaximum(); 170 } 171 172 175 public boolean cancel() throws Exception { 176 return false; 177 } 178 179 182 public static final class LoadItem<E> { 183 public DataTable table; 184 185 public E data; 186 187 public LoadItem(DataTable table, E data) { 188 this.table = table; 189 this.data = data; 190 } 191 } 192 193 196 private class LoadNotifier implements Runnable { 197 private boolean pending = false; 198 199 LoadNotifier() { 200 } 201 202 public synchronized void setPending(boolean pending) { 203 this.pending = pending; 204 } 205 206 public synchronized boolean isPending() { 207 return pending; 208 } 209 210 public void run() { 211 synchronized (loadQueue) { 212 if (loadQueue.size() > 0) { 213 LoadItem[] items = (LoadItem[]) loadQueue 214 .toArray(new LoadItem[loadQueue.size()]); 215 loadQueue.clear(); 216 loadData(items); 217 } 218 setPending(false); 219 } 220 } 221 } 222 } 223 | Popular Tags |