KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > proactive > examples > binarytree > TreeApplet


1 /*
2 * ################################################################
3 *
4 * ProActive: The Java(TM) library for Parallel, Distributed,
5 * Concurrent computing with Security and Mobility
6 *
7 * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
8 * Contact: proactive-support@inria.fr
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
23 * USA
24 *
25 * Initial developer(s): The ProActive Team
26 * http://www.inria.fr/oasis/ProActive/contacts.html
27 * Contributor(s):
28 *
29 * ################################################################
30 */

31 package org.objectweb.proactive.examples.binarytree;
32
33 import java.io.IOException JavaDoc;
34
35 import org.apache.log4j.Logger;
36 import org.objectweb.proactive.ActiveObjectCreationException;
37 import org.objectweb.proactive.ProActive;
38 import org.objectweb.proactive.core.node.NodeException;
39
40 /**
41  * <p>
42  * The binary tree is an a recursive data structure. A tree is
43  * composed of a root node, and each node has two potential child
44  * nodes. Here, each node is an active object, allowing large data
45  * structures to be distributed aver the network.
46  * </p>
47  *
48  * @author ProActive Team
49  * @version 1.0, 2001/10/23
50  * @since ProActive 0.9
51  *
52  */

53 public class TreeApplet extends org.objectweb.proactive.examples.StandardFrame {
54     
55         static Logger logger = Logger.getLogger(TreeApplet.class.getName());
56     private javax.swing.JPanel JavaDoc rootPanel;
57     private javax.swing.Box JavaDoc pCmd;
58     private javax.swing.JPanel JavaDoc searchResult;
59     private javax.swing.JButton JavaDoc bAdd;
60     private javax.swing.JButton JavaDoc bSearch;
61     private javax.swing.JButton JavaDoc bDump;
62     private javax.swing.JTextField JavaDoc tNode;
63     private javax.swing.JTextField JavaDoc tKey;
64     private javax.swing.JTextField JavaDoc tValue;
65     private javax.swing.JTextField JavaDoc tKeysNb;
66     private javax.swing.JScrollPane JavaDoc scrollTree;
67     private javax.swing.JRadioButton JavaDoc continuation;
68     private TreeDisplay display;
69     private TreePanel treePanel;
70     private SearchPane searchPane;
71     // Flag who indicates if Automataic Continuations
72
// are enabled
73
private boolean AC = false;
74     // ArrayList who contains keys to do a multi-research
75
private java.util.ArrayList JavaDoc keys;
76
77     private java.util.ArrayList JavaDoc futurs;
78
79
80     public TreeApplet(){
81     super();
82     }
83
84
85     public TreeApplet(String JavaDoc name, Integer JavaDoc width, Integer JavaDoc height) {
86     super(name, width.intValue(), height.intValue());
87     verticalSplitPane.addMouseListener(new java.awt.event.MouseAdapter JavaDoc() {
88         public void mouseEntered(java.awt.event.MouseEvent JavaDoc e) {
89         refresh();
90         }
91     });
92     // Create the DisplayManager
93
try {
94         display = new TreeDisplay(this);
95         display = (TreeDisplay) org.objectweb.proactive.ProActive.turnActive(display);
96         treePanel.setDisplay(display);
97     } catch (Exception JavaDoc e) {
98         e.printStackTrace();
99     }
100     }
101
102     public static void main(String JavaDoc arg[]) {
103     try {
104         org.objectweb.proactive.ProActive.newActive(TreeApplet.class.getName(),
105                             new Object JavaDoc[] {"Binary Tree",
106                                       new Integer JavaDoc(900),
107                                       new Integer JavaDoc(600)});
108     } catch (ActiveObjectCreationException e) {
109     } catch (NodeException e) {
110     }
111     }
112
113     public void displayTree() {
114     if (treePanel != null) {
115         javax.swing.SwingUtilities.invokeLater(new Runnable JavaDoc() {
116
117         public void run() {
118             treePanel.repaint();
119         }
120         });
121     }
122     }
123
124     protected void start() {
125     }
126
127     protected javax.swing.JPanel JavaDoc createRootPanel() {
128     rootPanel = new javax.swing.JPanel JavaDoc(new java.awt.BorderLayout JavaDoc());
129
130     javax.swing.JPanel JavaDoc westPanel = new javax.swing.JPanel JavaDoc(new java.awt.BorderLayout JavaDoc());
131     pCmd = javax.swing.Box.createVerticalBox();
132
133     // Create Area
134
javax.swing.JPanel JavaDoc panel = new javax.swing.JPanel JavaDoc();
135     tNode = new javax.swing.JTextField JavaDoc("", 3);
136     javax.swing.JButton JavaDoc create = new javax.swing.JButton JavaDoc("Create Binary Tree");
137     create.addActionListener(new java.awt.event.ActionListener JavaDoc() {
138         public void actionPerformed(java.awt.event.ActionEvent JavaDoc e) {
139         String JavaDoc nodeNb = tNode.getText();
140         int nb = 0;
141         try {
142             // We re-initialize automatic continuations
143
continuation.setSelected(false);
144             AC = false;
145             nb = (new Integer JavaDoc(nodeNb)).intValue();
146             display.createTree(nb, AC);
147         }
148         catch (NumberFormatException JavaDoc ex) {
149             receiveMessage("You must enter an integer size of the tree!",
150                    java.awt.Color.red);
151         }
152         }
153     });
154     panel.add(create);
155     panel.add(new javax.swing.JLabel JavaDoc("Size:"));
156     panel.add(tNode);
157     pCmd.add(panel);
158
159     // Text Area
160
panel = new javax.swing.JPanel JavaDoc();
161     tKey = new javax.swing.JTextField JavaDoc("", 15);
162     panel.add(new javax.swing.JLabel JavaDoc("Key"));
163     panel.add(tKey);
164     pCmd.add(panel);
165
166     panel = new javax.swing.JPanel JavaDoc();
167     tValue = new javax.swing.JTextField JavaDoc("", 15);
168     panel.add(new javax.swing.JLabel JavaDoc("Value"));
169     panel.add(tValue);
170     pCmd.add(panel);
171
172     // Button placement
173
panel = new javax.swing.JPanel JavaDoc();
174     javax.swing.JButton JavaDoc bAdd = new javax.swing.JButton JavaDoc("Add");
175     bAdd.setToolTipText("Add a node to the tree");
176     bAdd.addActionListener(new java.awt.event.ActionListener JavaDoc() {
177
178         public void actionPerformed(java.awt.event.ActionEvent JavaDoc e) {
179         String JavaDoc key = tKey.getText();
180         String JavaDoc value = tValue.getText();
181         if (key == null || value == null) {
182             receiveMessage("You must specify a Key/Value couple!!!",
183                    java.awt.Color.red);
184         } else {
185             display.add(key, value, AC);
186         }
187         }
188     });
189     panel.add(bAdd);
190
191     javax.swing.JButton JavaDoc bSearch = new javax.swing.JButton JavaDoc("Search");
192     bSearch.setToolTipText("Research the value of the key");
193     bSearch.addActionListener(new java.awt.event.ActionListener JavaDoc() {
194
195         public void actionPerformed(java.awt.event.ActionEvent JavaDoc e) {
196         String JavaDoc key = tKey.getText();
197         if (key == null)
198             return;
199         tValue.setText((display.search(key)).toString());
200         }
201     });
202     panel.add(bSearch);
203
204     javax.swing.JButton JavaDoc bDump = new javax.swing.JButton JavaDoc("Dump tree");
205     bDump.addActionListener(new java.awt.event.ActionListener JavaDoc() {
206
207         public void actionPerformed(java.awt.event.ActionEvent JavaDoc e) {
208         displayTree();
209         }
210     });
211     panel.add(bDump);
212
213     pCmd.add(panel);
214
215     pCmd.add(javax.swing.Box.createVerticalStrut(30));
216
217     // Generate Keys to search
218
panel = new javax.swing.JPanel JavaDoc();
219     tKeysNb = new javax.swing.JTextField JavaDoc("", 3);
220     javax.swing.JButton JavaDoc generateK = new javax.swing.JButton JavaDoc("Generate Keys");
221     generateK.setToolTipText("Generate keys to research values");
222     generateK.addActionListener(new java.awt.event.ActionListener JavaDoc() {
223         public void actionPerformed(java.awt.event.ActionEvent JavaDoc e) {
224         String JavaDoc keyNb = tKeysNb.getText();
225         try {
226             int nb = (new Integer JavaDoc(keyNb)).intValue();
227             keys = display.getRandomKeys(nb);
228             searchPane.clear();
229             java.util.Iterator JavaDoc it = keys.iterator();
230             while (it.hasNext()) {
231             java.util.Vector JavaDoc curLine = new java.util.Vector JavaDoc();
232             String JavaDoc[] kv = new String JavaDoc[3];
233             kv[0] = (String JavaDoc) it.next();
234             kv[1] = "Unknown";
235             kv[2] = "";
236             searchPane.updateKeyValue(kv);
237             }
238         } catch (NumberFormatException JavaDoc ex) {
239             receiveMessage("You must enter an integer number of keys!",
240                    java.awt.Color.red);
241         }
242         }
243     });
244     panel.add(generateK);
245     panel.add(new javax.swing.JLabel JavaDoc("Number:"));
246     panel.add(tKeysNb);
247     pCmd.add(panel);
248
249     // Research Panel
250
searchPane = new SearchPane();
251     pCmd.add(searchPane);
252
253     // Automatic Continuations Button
254
panel = new javax.swing.JPanel JavaDoc();
255     continuation = new javax.swing.JRadioButton JavaDoc("Automatic Continuations");
256     continuation.setToolTipText("Enabled/Disabled Automatic Continuations");
257     continuation.addActionListener(new java.awt.event.ActionListener JavaDoc() {
258
259         public void actionPerformed(java.awt.event.ActionEvent JavaDoc e) {
260         if (AC) {
261             try {
262             ProActive.disableAC(display);
263             display.disableAC();
264             receiveMessage("Automatic continuation disabled...",
265                        new java.awt.Color JavaDoc(200, 100, 0));
266             AC = false;
267             }
268             catch (IOException JavaDoc e1) {
269             }
270         }
271         else {
272             try {
273             ProActive.enableAC(display);
274             display.enableAC();
275             receiveMessage("Automatic continuation enabled...",
276                        new java.awt.Color JavaDoc(200, 100, 0));
277             AC = true;
278             }
279             catch (IOException JavaDoc e1) {
280             }
281         }
282         }
283     });
284     panel.add(continuation);
285     pCmd.add(panel);
286
287     panel = new javax.swing.JPanel JavaDoc();
288     javax.swing.JButton JavaDoc search = new javax.swing.JButton JavaDoc("Search Values");
289     search.setToolTipText("Research values of the keys");
290     search.addActionListener(new java.awt.event.ActionListener JavaDoc() {
291         public void actionPerformed(java.awt.event.ActionEvent JavaDoc e) {
292         try {
293             java.util.Iterator JavaDoc it = keys.iterator();
294             java.util.Vector JavaDoc tab1 = new java.util.Vector JavaDoc();
295             while (it.hasNext()) {
296             String JavaDoc key = (String JavaDoc) it.next();
297             tab1.add(display.search(key));
298             }
299
300             int lng = keys.size();
301             java.util.ArrayList JavaDoc vKeys = new java.util.ArrayList JavaDoc();
302             java.util.ArrayList JavaDoc res = new java.util.ArrayList JavaDoc();
303             for (int i = 0; i < lng; i++) {
304             vKeys.add(new Integer JavaDoc(i));
305             }
306
307             for (int i = 0; i < lng; i++) {
308             int key = 0;
309             key = org.objectweb.proactive.ProActive.waitForAny(tab1);
310             res.add(new String JavaDoc[]{(String JavaDoc) (keys.get(((Integer JavaDoc)vKeys.remove(key)).intValue())), ((ObjectWrapper) tab1.get(key)).toString(), "" + i});
311             tab1.remove(key);
312             }
313
314             Thread JavaDoc t = new RefreshThread(res);
315             t.start();
316             
317             receiveMessage("Search in progress...",
318                    new java.awt.Color JavaDoc(200, 100, 100));
319         }
320         catch (NullPointerException JavaDoc ex) {
321             receiveMessage("You must have keys to search!", java.awt.Color.red);
322         }
323         }
324     });
325     panel.add(search);
326     pCmd.add(panel);
327
328     westPanel.add(pCmd, java.awt.BorderLayout.NORTH);
329     rootPanel.add(westPanel, java.awt.BorderLayout.WEST);
330
331     treePanel = new TreePanel(display);
332     scrollTree = new javax.swing.JScrollPane JavaDoc();
333     scrollTree.getViewport().add(treePanel);
334     rootPanel.add(scrollTree, java.awt.BorderLayout.CENTER);
335
336     return rootPanel;
337     }
338
339     public void refresh() {
340       verticalSplitPane.validate();
341       verticalSplitPane.repaint();
342     }
343
344     public class TreePanel extends javax.swing.JPanel JavaDoc {
345     private TreeDisplay display;
346
347     public TreePanel(TreeDisplay display) {
348         this.display = display;
349         setVisible(true);
350         setBackground(java.awt.Color.white);
351         addMouseListener(new java.awt.event.MouseAdapter JavaDoc() {
352         public void mouseEntered(java.awt.event.MouseEvent JavaDoc e) {
353             refresh();
354         }
355         });
356     }
357
358     public void repaint() {
359       logger.info(Thread.currentThread());
360       super.repaint();
361     }
362
363     public void setDisplay(TreeDisplay display) {
364         this.display = display;
365     }
366
367     public void paintComponent(java.awt.Graphics JavaDoc g) {
368         super.paintComponent(g);
369         try {
370         if (display != null) {
371             Tree tree = display.getTree();
372             if (tree != null) {
373             try {
374                 // Dimension depending to the depth of tree
375
int width = 300, height = 600;
376                 switch (tree.depth()) {
377                 case 0 :
378                 case 1 :
379                 case 2 :
380                 case 3 :
381                 case 4 :
382                 break;
383                 case 5 :
384                 height = 1200;
385                 break;
386                 case 6 :
387                 height = 2400;
388                 break;
389                 case 7 :
390                 case 8 :
391                 case 9 :
392                 height = 5400;
393                 break;
394                 default :
395                 width = tree.depth() * 60;
396                 height = 5400;
397                 break;
398                 }
399                 java.awt.Dimension JavaDoc newSize = new java.awt.Dimension JavaDoc(height, width);
400                 if (!newSize.equals(getPreferredSize())) {
401                   setPreferredSize(newSize);
402                   scrollTree.getViewport().doLayout();
403                 }
404                 paintTree(g, tree, (int) height / 2, 30, tree.depth());
405             }
406             catch (NullPointerException JavaDoc e) {}
407             }
408         }
409         }
410         catch (Exception JavaDoc e) {}
411     }
412     
413     public void paintTree(java.awt.Graphics JavaDoc g, Tree tree, int x, int y, int depth) {
414         if (tree != null && tree.getKey() != null) {
415         // Analyse of the key size to paint the node
416
int keySize = 5;
417         java.text.StringCharacterIterator JavaDoc it1
418             = new java.text.StringCharacterIterator JavaDoc(tree.getKey());
419         while (it1.current() != java.text.StringCharacterIterator.DONE) {
420             char currentChar = it1.next();
421             if (currentChar == 'i' || currentChar == 'l')
422             keySize = keySize + 3;
423             else if (currentChar == 'j' || currentChar == 'f')
424             keySize = keySize + 6;
425             else if (currentChar == 'm' || currentChar == 'w')
426             keySize = keySize + 10;
427             else
428             keySize = keySize + 9;
429         }
430
431         // Analyse of the value size to paint the node
432
int valueSize = 5;
433         java.text.StringCharacterIterator JavaDoc it2
434             = new java.text.StringCharacterIterator JavaDoc(tree.getValue());
435         while (it2.current() != java.text.StringCharacterIterator.DONE) {
436             char currentChar = it2.next();
437             if (currentChar == 'i' || currentChar == 'l')
438             valueSize = valueSize + 3;
439             else if (currentChar == 'j' || currentChar == 'f')
440             valueSize = valueSize + 6;
441             else if (currentChar == 'm' || currentChar == 'w')
442             valueSize = valueSize + 10;
443             else
444             valueSize = valueSize + 9;
445         }
446
447         int size;
448         if (valueSize > keySize)
449             size = valueSize;
450         else
451             size = keySize;
452
453         g.setColor(new java.awt.Color JavaDoc(240, 240, 240));
454         g.fillRoundRect(x - size / 2, y - 10, size, 40, 35, 35);
455
456         g.setColor(java.awt.Color.black);
457         g.drawRoundRect(x - size / 2, y - 10, size, 40, 35, 35);
458         g.drawLine(x - size / 2, y + 10, x - size / 2 + size, y + 10);
459         g.drawString(tree.getKey(), x - size / 2 + 5, y + 5);
460         
461         g.setColor(java.awt.Color.blue);
462         g.drawString(tree.getValue(), x - size / 2 + 5, y + 25);
463         
464         //Angle value
465
int angle = 65;
466         if (depth > 0) {
467             switch (depth) {
468             case 1 :
469             break;
470             case 2 :
471             angle = 50;
472             break;
473             case 3 :
474             angle = 35;
475             break;
476             case 4 :
477             angle = 20;
478             break;
479             case 5 :
480             angle = 10;
481             break;
482             case 6 :
483             angle = 5;
484             break;
485             case 7 :
486             angle = 2;
487             break;
488             default :
489             depth = 7;
490             angle = 2;
491             }
492         }
493
494         try {
495             int rightX = (int) (x + 50 / Math.tan(Math.toRadians(angle))),
496             rightY = y + 60;
497
498             paintTree(g, tree.getRight(), rightX, rightY, depth - 1);
499
500             g.setColor(java.awt.Color.lightGray);
501             g.drawLine(x + 4, y + 30, rightX + 1, rightY - 10);
502             g.drawLine(x + 2, y + 30, rightX - 1, rightY - 10);
503
504             g.setColor(java.awt.Color.black);
505             g.drawLine(x + 3, y + 30, rightX, rightY - 10);
506         }
507         catch (NullPointerException JavaDoc e) {
508             //We stop the right iteration in tree, if a
509
//NullPointerException is detected
510
}
511
512         try {
513             int leftX = (int) (x + 50 / Math.tan(Math.toRadians(180 - angle))),
514             leftY = y + 60;
515
516             paintTree(g, tree.getLeft(), leftX, leftY, depth - 1);
517
518             g.setColor(java.awt.Color.lightGray);
519             g.drawLine(x - 4, y + 30, leftX - 1, leftY - 10);
520             g.drawLine(x - 2, y + 30, leftX + 1, leftY - 10);
521
522             g.setColor(java.awt.Color.black);
523             g.drawLine(x - 3, y + 30, leftX, leftY - 10);
524         }
525         catch (NullPointerException JavaDoc e) {
526             //We stop the left iteration in tree, if a
527
//NullPointerException is detected
528
}
529         }
530     }
531         
532     }
533
534     public class RefreshThread extends Thread JavaDoc {
535     
536     java.util.ArrayList JavaDoc list;
537     
538     public RefreshThread (java.util.ArrayList JavaDoc list) {
539         this.list = list;
540     }
541             
542     public void run() {
543         java.util.Iterator JavaDoc it = list.iterator();
544         while (it.hasNext()){
545         try {
546             Thread.sleep(500);
547             searchPane.updateKeyValue((String JavaDoc[])(it.next()));
548         }
549         catch (InterruptedException JavaDoc ex) {
550         }
551         }
552     }
553     }
554 }
555
Popular Tags