KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SortItem


1 /*
2  * @(#)SortItem.java 1.20 06/02/22
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 /*
38  * @(#)SortItem.java 1.20 06/02/22
39  */

40
41 import java.awt.*;
42 import java.awt.event.*;
43 import java.io.InputStream JavaDoc;
44 import java.util.Hashtable JavaDoc;
45 import java.net.*;
46
47 /**
48  * A simple applet class to demonstrate a sort algorithm.
49  * You can specify a sorting algorithm using the "alg"
50  * attribyte. When you click on the applet, a thread is
51  * forked which animates the sorting algorithm.
52  *
53  * @author James Gosling
54  * @version 1.20, 02/22/06
55  */

56 public class SortItem
57     extends java.applet.Applet JavaDoc
58     implements Runnable JavaDoc, MouseListener {
59
60     /**
61      * The thread that is sorting (or null).
62      */

63     private Thread JavaDoc kicker;
64
65     /**
66      * The array that is being sorted.
67      */

68     int arr[];
69
70     /**
71      * The high water mark.
72      */

73     int h1 = -1;
74
75     /**
76      * The low water mark.
77      */

78     int h2 = -1;
79
80     /**
81      * The name of the algorithm.
82      */

83     String JavaDoc algName;
84
85     /**
86      * The sorting algorithm (or null).
87      */

88     SortAlgorithm algorithm;
89
90     Dimension initialSize = null;
91
92     /**
93      * Fill the array with random numbers from 0..n-1.
94      */

95     void scramble() {
96     initialSize = getSize();
97     int a[] = new int[initialSize.height / 2];
98     double f = initialSize.width / (double) a.length;
99
100     for (int i = a.length; --i >= 0;) {
101         a[i] = (int)(i * f);
102     }
103     for (int i = a.length; --i >= 0;) {
104         int j = (int)(i * Math.random());
105         int t = a[i];
106         a[i] = a[j];
107         a[j] = t;
108     }
109     arr = a;
110     }
111
112     /**
113      * Pause a while.
114      * @see SortAlgorithm
115      */

116     void pause() {
117     pause(-1, -1);
118     }
119
120     /**
121      * Pause a while, and draw the high water mark.
122      * @see SortAlgorithm
123      */

124     void pause(int H1) {
125     pause(H1, -1);
126     }
127
128     /**
129      * Pause a while, and draw the low&high water marks.
130      * @see SortAlgorithm
131      */

132     void pause(int H1, int H2) {
133     h1 = H1;
134     h2 = H2;
135     if (kicker != null) {
136         repaint();
137     }
138     try {Thread.sleep(20);} catch (InterruptedException JavaDoc e){}
139     }
140
141     /**
142      * Initialize the applet.
143      */

144     public void init() {
145     String JavaDoc at = getParameter("alg");
146     if (at == null) {
147         at = "BubbleSort";
148     }
149
150     algName = at + "Algorithm";
151     scramble();
152
153     resize(100, 100);
154     addMouseListener(this);
155     }
156
157     public void start() {
158         h1 = h2 = -1;
159         scramble();
160         repaint();
161         showStatus(getParameter("alg"));
162     }
163
164     /**
165      * Deallocate resources of applet.
166      */

167     public void destroy() {
168         removeMouseListener(this);
169     }
170
171     /**
172      * Paint the array of numbers as a list
173      * of horizontal lines of varying lengths.
174      */

175     public void paint(Graphics g) {
176         int a[] = arr;
177         int y = 0;
178         int deltaY = 0, deltaX = 0, evenY = 0, evenX = 0;
179
180         Dimension currentSize = getSize();
181         int currentHeight = currentSize.height;
182         int currentWidth = currentSize.width;
183
184         // Check to see if the applet has been resized since it
185
// started running. If so, need the deltas to make sure
186
// the applet is centered in its containing panel.
187
// The evenX and evenY are because the high and low
188
// watermarks are calculated from the top, but the rest
189
// of the lines are calculated from the bottom, which
190
// can lead to a discrepancy if the window is not an
191
// even size.
192
if (!currentSize.equals(initialSize)) {
193             evenY = (currentHeight - initialSize.height) % 2;
194             evenX = (currentWidth - initialSize.width) % 2;
195             deltaY = (currentHeight - initialSize.height) / 2;
196             deltaX = (currentWidth - initialSize.width) / 2;
197
198             if (deltaY < 0) {
199                 deltaY = 0;
200                 evenY = 0;
201             }
202             if (deltaX < 0) {
203                 deltaX = 0;
204                 evenX = 0;
205             }
206         }
207
208     // Erase old lines
209
g.setColor(getBackground());
210     y = currentHeight - deltaY - 1;
211     for (int i = a.length; --i >= 0; y -= 2) {
212         g.drawLine(deltaX + arr[i], y, currentWidth, y);
213     }
214
215     // Draw new lines
216
g.setColor(Color.black);
217     y = currentHeight - deltaY - 1;
218     for (int i = a.length; --i >= 0; y -= 2) {
219         g.drawLine(deltaX, y, deltaX + arr[i], y);
220     }
221
222     if (h1 >= 0) {
223         g.setColor(Color.red);
224         y = deltaY + evenY + h1 * 2 + 1;
225         g.drawLine(deltaX, y, deltaX + initialSize.width, y);
226     }
227     if (h2 >= 0) {
228         g.setColor(Color.blue);
229         y = deltaY + evenY + h2 * 2 + 1;
230         g.drawLine(deltaX, y, deltaX + initialSize.width, y);
231     }
232     }
233
234     /**
235      * Update without erasing the background.
236      */

237     public void update(Graphics g) {
238     paint(g);
239     }
240
241     /**
242      * Run the sorting algorithm. This method is
243      * called by class Thread once the sorting algorithm
244      * is started.
245      * @see java.lang.Thread#run
246      * @see SortItem#mouseUp
247      */

248     public void run() {
249     try {
250         if (algorithm == null) {
251         algorithm = (SortAlgorithm)Class.forName(algName).newInstance();
252         algorithm.setParent(this);
253         }
254         algorithm.init();
255         algorithm.sort(arr);
256     } catch(Exception JavaDoc e) {
257     }
258     }
259
260     /**
261      * Stop the applet. Kill any sorting algorithm that
262      * is still sorting.
263      */

264     public synchronized void stop() {
265     if (algorithm != null){
266             try {
267         algorithm.stop();
268             } catch (IllegalThreadStateException JavaDoc e) {
269                 // ignore this exception
270
}
271             kicker = null;
272     }
273     }
274
275     /**
276      * For a Thread to actually do the sorting. This routine makes
277      * sure we do not simultaneously start several sorts if the user
278      * repeatedly clicks on the sort item. It needs to be
279      * synchronized with the stop() method because they both
280      * manipulate the common kicker variable.
281      */

282     private synchronized void startSort() {
283     if (kicker == null || !kicker.isAlive()) {
284         kicker = new Thread JavaDoc(this);
285         kicker.start();
286     }
287     }
288
289
290     public void mouseClicked(MouseEvent e) {
291         showStatus(getParameter("alg"));
292     }
293
294     public void mousePressed(MouseEvent e) {
295     }
296
297     /**
298      * The user clicked in the applet. Start the clock!
299      */

300     public void mouseReleased(MouseEvent e) {
301         startSort();
302         e.consume();
303     }
304
305     public void mouseEntered(MouseEvent e) {
306     }
307
308     public void mouseExited(MouseEvent e) {
309     }
310
311     public String JavaDoc getAppletInfo() {
312         return "Title: SortDemo \nAuthor: James Gosling 1.17f, 10 Apr 1995 \nA simple applet class to demonstrate a sort algorithm. \nYou can specify a sorting algorithm using the 'alg' attribute. \nWhen you click on the applet, a thread is forked which animates \nthe sorting algorithm.";
313     }
314
315     public String JavaDoc[][] getParameterInfo() {
316         String JavaDoc[][] info = {
317           {"alg", "string", "The name of the algorithm to run. You can choose from the provided algorithms or suppply your own, as long as the classes are runnable as threads and their names end in 'Algorithm.' BubbleSort is the default. Example: Use 'QSort' to run the QSortAlgorithm class."}
318         };
319         return info;
320     }
321 }
322
323
Popular Tags