JThreadKit Home
Source File(s):
SizeMonitoredDemo.java
SizeDemoApplet.java
source.zip (all files)

SizeMonitoredDemo.java

  1: package com.jtkdemo;
  2: 
  3: import java.util.*;
  4: import java.awt.*;
  5: import java.awt.event.*;
  6: import javax.swing.*;
  7: import javax.swing.border.*;
  8: import com.jthreadkit.*;
  9: import com.jthreadkit.fifo.*;
 10: import com.jthreadkit.collection.*;
 11: import com.jthreadkit.swing.*;
 12: 
 13: public class SizeMonitoredDemo extends JPanel {
 14: 
 15:     private JButton startButton;
 16:     private JButton clearButton;
 17:     private JTKTextArea resultsTA;
 18:     private JTKTextArea listenerTA;
 19:     private JLabel statusBar;
 20:     private JRadioButton mapBox;
 21:     private JRadioButton listBox;
 22:     private JRadioButton setBox;
 23:     private JRadioButton collectionBox;
 24:     private SizeChangeListener scl;
 25:     private SizeMonitoredMap smm;
 26:     private SizeMonitoredList sml;
 27:     private SizeMonitoredSet sms;
 28:     private SizeMonitoredCollection smc;
 29:     private Runnable enableScreenRunnable;
 30:     private Runnable mapRunnable;
 31:     private Runnable listRunnable;
 32:     private Runnable setRunnable;
 33:     private Runnable collectionRunnable;
 34:     private int sleepLen = 2000;
 35:     private final int MAP_DEMO = 1;
 36:     private final int LIST_DEMO = 2;
 37:     private final int SET_DEMO = 3;
 38:     private final int COLLECTION_DEMO = 4;
 39:     private final String[] itemsArray = {"one", "two", "three", "four",
 40:                                          "five"};
 41:         
 42:     public SizeMonitoredDemo() {
 43:         
 44:         this.setLayout(new BorderLayout(5, 5));
 45:         Component leftPanel = buildLeftPanel();
 46:         Component rightPanel = buildRightPanel();
 47:         Component topPanel = buildTopPanel();
 48:         Component bottomPanel = buildBottomPanel();
 49:         JSplitPane splitPane = 
 50:             new JSplitPane(
 51:                     JSplitPane.HORIZONTAL_SPLIT, 
 52:                     true, 
 53:                     leftPanel, 
 54:                     rightPanel
 55:                 );
 56:         this.add(topPanel, BorderLayout.NORTH); 
 57:         this.add(bottomPanel, BorderLayout.SOUTH);
 58:         this.add(splitPane, BorderLayout.CENTER);
 59:         this.add(new JLabel(""), BorderLayout.EAST);
 60:         this.add(new JLabel(""), BorderLayout.WEST);
 61:         
 62:         // Create a SizeChangeListener using an Anonymous Inner Class.  Once
 63:         // a demo is started, this listener will be added to the SizeMonitored
 64:         // that is created by that demo.  The sizeChanged() method is then 
 65:         // called every time the SizeMonitored has a change in size, and that 
 66:         // change is displayed in the Listener text area.
 67:         scl = new SizeChangeListener() {
 68:                 public void sizeChanged(SizeMonitored sizeMon, int newSize) {
 69:                     updateLTA("Size now = " + newSize);
 70:                 }   
 71:             };
 72:         
 73:         createRunnables();
 74:     }
 75: 
 76:     private void createRunnables() {
 77:         enableScreenRunnable = new Runnable() {
 78:                 public void run() {
 79:                     enableScreen();
 80:                 }
 81:             };
 82:             
 83:         mapRunnable = new Runnable() {
 84:                 public void run() {
 85:                     Thread.currentThread().setName("Map_Main_Thread");
 86:                     createMap();
 87:                 }
 88:             };
 89:             
 90:         listRunnable = new Runnable() {
 91:                 public void run() {
 92:                     Thread.currentThread().setName("List_Main_Thread");
 93:                     createList();
 94:                 }
 95:             };
 96:             
 97:         setRunnable = new Runnable() {
 98:                 public void run() {
 99:                     Thread.currentThread().setName("Set_Main_Thread");
100:                     createSet();
101:                 }
102:             };
103:         
104:         collectionRunnable = new Runnable() {
105:                 public void run() {
106:                     Thread.currentThread().setName("Collection_Main_Thread");
107:                     createCollection();
108:                 }
109:             };
110:     }
111:     
112:     private Component buildTopPanel() {
113:         JPanel buttonP = new JPanel();
114:         startButton = new JButton("Start");
115:         startButton.setMnemonic('S');
116:         startButton.addActionListener(new ActionListener() {
117:                 public void actionPerformed(ActionEvent e) {
118:                     startDemo();
119:                 }
120:             });
121:         clearButton = new JButton("Clear");
122:         clearButton.setMnemonic('C');
123:         clearButton.addActionListener(new ActionListener() {
124:                 public void actionPerformed(ActionEvent e) {
125:                     // Directly set the text on the JTKTextAreas since we 
126:                     // know that we are the event thread...
127:                     resultsTA.getTextArea().setText("");
128:                     listenerTA.getTextArea().setText("");
129:                 }
130:             });
131:         buttonP.add(startButton);
132:         buttonP.add(clearButton);
133:         return buttonP; 
134:     }
135:     
136:     private Component buildBottomPanel() {
137:         statusBar = new JLabel(" Idle...");
138:         statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
139:         return statusBar;   
140:     }
141: 
142:     private Component buildLeftPanel() {
143:         JPanel innerLeftP = new JPanel(new GridLayout(0, 1));
144:         JPanel leftP = new JPanel(new BorderLayout());
145:         innerLeftP.setBorder(BorderFactory.createTitledBorder("Type"));
146:         mapBox = new JRadioButton("Map", true);
147:         mapBox.setMnemonic('M');
148:         listBox = new JRadioButton("List");
149:         listBox.setMnemonic('L');
150:         setBox = new JRadioButton("Set");
151:         setBox.setMnemonic('E');
152:         collectionBox = new JRadioButton("Collection   ");
153:         collectionBox.setMnemonic('O');
154:         ButtonGroup bg = new ButtonGroup();
155:         bg.add(mapBox);
156:         bg.add(listBox);
157:         bg.add(setBox);
158:         bg.add(collectionBox);
159:         innerLeftP.add(mapBox);
160:         innerLeftP.add(listBox);
161:         innerLeftP.add(setBox);
162:         innerLeftP.add(collectionBox);
163:         listenerTA = new JTKTextArea(new JTextArea());
164:         listenerTA.getTextArea().setEditable(false);
165:         listenerTA.getTextArea().setForeground(Color.red);
166:         JScrollPane sp = new JScrollPane(listenerTA.getTextArea());
167:         sp.setBorder(BorderFactory.createTitledBorder("Listener"));
168:         leftP.add(innerLeftP, BorderLayout.NORTH);
169:         leftP.add(sp, BorderLayout.CENTER);
170:         return leftP;
171:     }
172: 
173:     private Component buildRightPanel() {
174:         JPanel rightP = new JPanel(new BorderLayout());
175:         resultsTA = new JTKTextArea(new JTextArea());
176:         resultsTA.getTextArea().setEditable(false);
177:         JScrollPane sp = new JScrollPane(resultsTA.getTextArea());
178:         sp.setBorder(BorderFactory.createTitledBorder("Results"));
179:         return sp;
180:     }
181: 
182:     private void disableScreen() {
183:         statusBar.setText(" Running...");
184:         startButton.setEnabled(false);
185:         clearButton.setEnabled(false);
186:         mapBox.setEnabled(false);
187:         listBox.setEnabled(false);
188:         setBox.setEnabled(false);
189:         collectionBox.setEnabled(false);
190:     }
191:     
192:     private void enableScreen() {
193:         statusBar.setText(" Idle...");
194:         startButton.setEnabled(true);
195:         clearButton.setEnabled(true);
196:         mapBox.setEnabled(true);
197:         listBox.setEnabled(true);
198:         setBox.setEnabled(true);
199:         collectionBox.setEnabled(true); 
200:     }
201: 
202:     private void startDemo() {
203:         disableScreen();
204:         int type = getDemoType();
205:         // create the appropriate object and start the demo
206:         createDemoObject(type);
207:     }
208: 
209:     private void createDemoObject(int type) {
210:         switch ( type ) {
211:             case -1:
212:                 // no type selected
213:                 showErrorMessage("Please select a demo type!");
214:                 enableScreen();
215:                 break;
216:             case 1:
217:                 // map
218:                 ThreadTools.execute(mapRunnable);
219:                 break;
220:             case 2:
221:                 // list
222:                 ThreadTools.execute(listRunnable);
223:                 break;
224:             case 3:
225:                 // set
226:                 ThreadTools.execute(setRunnable);
227:                 break;
228:             case 4:
229:                 // collection
230:                 ThreadTools.execute(collectionRunnable);
231:                 break;
232:             default:
233:                 showErrorMessage("\'" + type + "\' is an invalid type!");
234:         }   
235:     }
236:     /**
237:      * Creates a SizeMonitoredMap using a HashMap behind the scenes.  This
238:      * method will also fire off a helper thread which will block by calling
239:      * waitForSizeToClimbTo(5), at which point it will begin removing objects
240:      * from the SizeMonitoredMap.
241:      */
242:     private void createMap() {
243:         try {
244:             updateRTA("Starting the SizeMonitoredMap demo...\n", false);
245:             Thread.sleep(sleepLen);
246:             // create a SizeMonitoredMap
247:             updateRTA("creating a SizeMonitoredMap using a HashMap behind " +
248:                 "the scenes...", true);
249:             smm = new WrappedSizeMonitoredMap(new HashMap());
250:             Thread.sleep(sleepLen);
251:             updateRTA("adding a SizeChangeListener.  All size changes will " +
252:                 "be displayed in the listener text area...", true);
253:             smm.addSizeChangeListener(scl);
254:             Thread.sleep(sleepLen);
255:             updateRTA("will now begin adding key/value pairs to the " +
256:                 "SizeMonitoredMap...", true);
257:             Thread.sleep(sleepLen);
258:             // start a helper thread to remove items
259:             Thread thread = startMapHelper();
260:             thread.start();
261:             // give the other thread a chance to start
262:             Thread.sleep(50);   
263:             for ( int i = 0; i < itemsArray.length; i++ ) {
264:                 updateRTA("putting key: new Integer(" + (i + 1) + "), " +
265:                     "value: \"" + itemsArray[i] + "\" pair into the " +
266:                     "SizeMonitoredMap...", true);
267:                 smm.put(new Integer(i + 1), itemsArray[i]);
268:                 if ( i < (itemsArray.length - 1) ) {
269:                     Thread.sleep(sleepLen);
270:                 }
271:             }
272:             // wait for the helper to finish up!
273:             thread.join();
274:         } catch ( Exception x ) {
275:             x.printStackTrace();    
276:         }
277:     }
278:     /**
279:      * Creates a SizeMonitoredList using an ArrayList behind the scenes.
280:      * This method will also fire off a helper thread which will block by 
281:      * calling waitForSizeToClimbTo(5), at which point it will begin removing 
282:      * objects from the SizeMonitoredList.
283:      */
284:     private void createList() {
285:         try {
286:             updateRTA("Starting the SizeMonitoredList demo...\n", false);
287:             Thread.sleep(sleepLen);
288:             // create a SizeMonitoredList
289:             updateRTA("creating a SizeMonitoredList using an ArrayList " +
290:                 "behind the scenes...", true);
291:             sml = new WrappedSizeMonitoredList(new ArrayList());
292:             Thread.sleep(sleepLen);
293:             updateRTA("adding a SizeChangeListener.  All size changes will " +
294:                 "be displayed in the listener text area...", true);
295:             sml.addSizeChangeListener(scl);
296:             Thread.sleep(sleepLen);
297:             updateRTA("will now begin adding Strings to the SizeMonitored" +
298:                 "List...", true);
299:             Thread.sleep(sleepLen);
300:             // start a helper thread to remove items
301:             Thread thread = startListHelper();
302:             thread.start();
303:             // give the other thread a chance to start
304:             Thread.sleep(50);   
305:             for ( int i = 0; i < itemsArray.length; i++ ) {
306:                 updateRTA("adding String \"" + itemsArray[i] + "\" to the " +
307:                     "SizeMonitoredList...", true);
308:                 sml.add(itemsArray[i]);
309:                 if ( i < (itemsArray.length - 1) ) {
310:                     Thread.sleep(sleepLen);
311:                 }
312:             }
313:             // wait for the helper to finish up!
314:             thread.join();
315:         } catch ( Exception x ) {
316:             x.printStackTrace();    
317:         }
318:     }
319:     /**
320:      * Creates a SizeMonitoredSet using a HashSet behind the scenes.
321:      * This method will also fire off a helper thread which will block by 
322:      * calling waitForSizeToClimbTo(5), at which point it will begin removing 
323:      * objects from the SizeMonitoredSet.
324:      */
325:     private void createSet() {
326:         try {
327:             updateRTA("Starting the SizeMonitoredSet demo...\n", false);
328:             Thread.sleep(sleepLen);
329:             // create a SizeMonitoredSet
330:             updateRTA("creating a SizeMonitoredSet using a HashSet behind " +
331:                 "the scenes...", true);
332:             sms = new WrappedSizeMonitoredSet(new HashSet());
333:             Thread.sleep(sleepLen);
334:             updateRTA("adding a SizeChangeListener.  All size changes will " +
335:                 "be displayed in the listener text area...", true);
336:             sms.addSizeChangeListener(scl);
337:             Thread.sleep(sleepLen);
338:             updateRTA("will now begin adding Strings to the SizeMonitored" +
339:                 "Set...", true);
340:             Thread.sleep(sleepLen);
341:             // start a helper thread to remove items
342:             Thread thread = startSetHelper();
343:             thread.start();
344:             // give the other thread a chance to start
345:             Thread.sleep(50);   
346:             for ( int i = 0; i < itemsArray.length; i++ ) {
347:                 updateRTA("adding String \"" + itemsArray[i] + "\" to the" +
348:                     " SizeMonitoredSet...", true);
349:                 sms.add(itemsArray[i]);
350:                 if ( i < (itemsArray.length - 1) ) {
351:                     Thread.sleep(sleepLen);
352:                 }
353:             }
354:             // wait for the helper to finish up!
355:             thread.join();
356:         } catch ( Exception x ) {
357:             x.printStackTrace();    
358:         }
359:     }
360:     /**
361:      * Creates a SizeMonitoredCollection using an ArrayList behind the 
362:      * scenes.  This method will also fire off a helper thread which will 
363:      * block by calling waitForSizeToClimbTo(5), at which point it will begin 
364:      * removing objects from the SizeMonitoredCollection.
365:      */
366:     private void createCollection() {
367:         try {
368:             updateRTA("Starting the SizeMonitoredCollection demo...\n", false);
369:             Thread.sleep(sleepLen);
370:             // create a SizeMonitoredCollection
371:             updateRTA("creating a SizeMonitoredCollection using a LinkedList" +
372:                 " behind the scenes...", true);
373:             smc = new WrappedSizeMonitoredCollection(new LinkedList());
374:             Thread.sleep(sleepLen);
375:             updateRTA("adding a SizeChangeListener.  All size changes will " +
376:                 "be displayed in the listener text area...", true);
377:             smc.addSizeChangeListener(scl);
378:             Thread.sleep(sleepLen);
379:             updateRTA("will now begin adding Strings to the SizeMonitored" +
380:                 "Collection...", true);
381:             Thread.sleep(sleepLen);
382:             // start a helper thread to remove items
383:             Thread thread = startCollectionHelper();
384:             thread.start();
385:             // give the other thread a chance to start
386:             Thread.sleep(50);   
387:             for ( int i = 0; i < itemsArray.length; i++ ) {
388:                 updateRTA("adding String \"" + itemsArray[i] + "\" to the " +
389:                     "SizeMonitoredCollection...", true);
390:                 smc.add(itemsArray[i]);
391:                 if ( i < (itemsArray.length - 1) ) {
392:                     Thread.sleep(sleepLen);
393:                 }
394:             }
395:             // wait for the helper to finish up!
396:             thread.join();
397:         } catch ( Exception x ) {
398:             x.printStackTrace();    
399:         }
400:     }
401: 
402:     private Thread startMapHelper() {
403:         Thread t = new Thread(new Runnable() {
404:                 public void run() {
405:                     // call waitUntilSizeIs
406:                     try {
407:                         updateRTA("will wait until the size climbs to 5.  It " +
408:                             "will then start removing items from the Size" +
409:                             "MonitoredMap...", true);
410:                         smm.waitForSizeToClimbTo(5);
411:                         for ( int i = 0; i < itemsArray.length; i++ ) {
412:                             updateRTA("removing: \"" + itemsArray[i] + "\"",
413:                                       true);
414:                             Object remObj = smm.remove(new Integer(i + 1));
415:                             if ( i < (itemsArray.length - 1) ) {
416:                                 Thread.sleep(sleepLen); 
417:                             }
418:                         }
419:                         updateRTA("\nFinished!!!\n", false);
420:                         SwingUtilities.invokeLater(enableScreenRunnable);
421:                     } catch ( Exception x ) {
422:                         x.printStackTrace();
423:                     }   
424:                 }
425:             }, "Map_Helper_Thread");
426:         return t;
427:     }
428: 
429:     private Thread startListHelper() {
430:         Thread t = new Thread(new Runnable() {
431:                 public void run() {
432:                     // call waitUntilSizeIs
433:                     try {
434:                         updateRTA("will wait until the size climbs to 5.  It " +
435:                             "will then start removing items from the Size" +
436:                             "Monitored List...", true);
437:                         sml.waitForSizeToClimbTo(5);
438:                         for ( int i = 0; i < itemsArray.length; i++ ) {
439:                             updateRTA("removing: \"" + itemsArray[i] + "\"",
440:                                       true);
441:                             boolean result = sml.remove(itemsArray[i]);
442:                             if ( i < (itemsArray.length - 1) ) {
443:                                 Thread.sleep(sleepLen); 
444:                             }
445:                         }
446:                         updateRTA("\nFinished!!!\n", false);
447:                         SwingUtilities.invokeLater(enableScreenRunnable);
448:                     } catch ( Exception x ) {
449:                         x.printStackTrace();
450:                     }   
451:                 }
452:             }, "List_Helper_Thread");
453:         return t;
454:     }
455:     
456:     private Thread startSetHelper() {
457:         Thread t = new Thread(new Runnable() {
458:                 public void run() {
459:                     // call waitUntilSizeIs
460:                     try {
461:                         updateRTA("will wait until the size climbs to 5.  It " +
462:                             "will then start removing items from the Size" +
463:                             "MonitoredSet...", true);
464:                         sms.waitForSizeToClimbTo(5);
465:                         for ( int i = 0; i < itemsArray.length; i++ ) {
466:                             updateRTA("removing: \"" + itemsArray[i] + "\"",
467:                                       true);
468:                             boolean result = sms.remove(itemsArray[i]);
469:                             if ( i < (itemsArray.length - 1) ) {
470:                                 Thread.sleep(sleepLen); 
471:                             }
472:                         }
473:                         updateRTA("\nFinished!!!\n", false);
474:                         SwingUtilities.invokeLater(enableScreenRunnable);
475:                     } catch ( Exception x ) {
476:                         x.printStackTrace();
477:                     }   
478:                 }
479:             }, "Set_Helper_Thread");
480:         return t;
481:     }
482:     
483:     private Thread startCollectionHelper() {
484:         Thread t = new Thread(new Runnable() {
485:                 public void run() {
486:                     // call waitUntilSizeIs
487:                     try {
488:                         updateRTA("will wait until the size climbs to 5.  " +
489:                             "It will then start removing items from the Size" +
490:                             "MonitoredCollection...", true);
491:                         smc.waitForSizeToClimbTo(5);
492:                         for ( int i = 0; i < itemsArray.length; i++ ) {
493:                             updateRTA("removing: \"" + itemsArray[i] + "\"",
494:                                       true);
495:                             boolean result = smc.remove(itemsArray[i]);
496:                             if ( i < (itemsArray.length - 1) ) {
497:                                 Thread.sleep(sleepLen); 
498:                             }
499:                         }
500:                         updateRTA("\nFinished!!!\n", false);
501:                         SwingUtilities.invokeLater(enableScreenRunnable);
502:                     } catch ( Exception x ) {
503:                         x.printStackTrace();
504:                     }   
505:                 }
506:             }, "Collection_Helper_Thread");
507:         return t;
508:     }
509: 
510:     private synchronized void updateRTA(String msg, boolean printThread) {
511:         String threadName = Thread.currentThread().getName();
512:         if ( printThread ) {
513:             resultsTA.appendSafely(threadName + " " + msg + "\n");
514:         } else {
515:             resultsTA.appendSafely(msg + "\n");
516:         }
517:     }
518: 
519:     private synchronized void updateLTA(String msg) {
520:         listenerTA.appendSafely(msg + "\n");
521:     }
522: 
523:     private int getDemoType() {
524:         int type = -1;
525:         if ( mapBox.isSelected() ) {
526:             type = 1;
527:         } else if ( listBox.isSelected() ) {
528:             type = 2;
529:         } else if ( setBox.isSelected() ) {
530:             type = 3;
531:         } else if ( collectionBox.isSelected() ) {
532:             type = 4;
533:         }
534:         return type;
535:     }
536: 
537:     private void showErrorMessage(String msg){
538:         
539:         JOptionPane pane = new JOptionPane();
540:         JOptionPane.showMessageDialog(
541:                     this, 
542:                     msg, 
543:                     "Alert", 
544:                     JOptionPane.ERROR_MESSAGE
545:                 ); 
546:     }
547: 
548:     public static void main(String[] args) {
549:         SizeMonitoredDemo demo = new SizeMonitoredDemo();
550:         Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
551:         JFrame f = new JFrame("SizeMonitored Demo");
552:         f.setContentPane(demo);
553:         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
554:         f.setSize(new Dimension(800, 500));
555:         f.setLocation((screenDim.width - f.getSize().width) / 2,
556:                       (screenDim.height - f.getSize().height) / 2);
557:         f.setVisible(true); 
558:     }
559: }
      

SizeDemoApplet.java

 1: package com.jtkdemo;
 2: 
 3: import java.awt.*;
 4: import java.applet.*;
 5: import java.awt.event.*;
 6: import javax.swing.*;
 7: import com.jtkdemo.*;
 8: import com.jthreadkit.*;
 9: import com.jthreadkit.fifo.*;
10: import com.jthreadkit.collection.*;
11: 
12: public class SizeDemoApplet extends Applet {
13:     public void init() {
14:         this.setBackground(Color.white);
15:         JButton button = new JButton("Run Demo");
16:         JPanel buttonP = new JPanel();
17:         buttonP.setBackground(Color.white);
18:         buttonP.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
19:         buttonP.add(button);
20:         this.add(buttonP, BorderLayout.SOUTH);
21:         button.addActionListener(new ActionListener() {
22:                 public void actionPerformed(ActionEvent e) {
23:                     startDemo();
24:                 }
25:             });
26:     }
27:     
28:     private void startDemo() {
29:         SizeMonitoredDemo demo = new SizeMonitoredDemo();
30:         JFrame f = new JFrame("SizeMonitoredDemo");
31:                 
32:         f.setContentPane(demo);
33:         f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
34:         Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
35:         f.setSize(800, 500);
36:         f.setLocation((screenDim.width - f.getSize().width) / 2,
37:                       (screenDim.height - f.getSize().height) / 2);
38:         f.setVisible(true);
39:     }
40: }
      
Back to top