01: import java.applet.Applet;
02: import java.awt.Color;
03: import java.awt.Graphics;
04: import java.awt.Graphics2D;
05: import java.awt.event.MouseEvent;
06: import java.awt.event.MouseAdapter;
07: import java.awt.event.MouseListener;
08: 
09: /**
10:    This applet animates the selection sort algorithm.
11: */
12: public class SelectionSortApplet extends Applet
13: {
14:    /**
15:       Constructs the applet and sets up the mouse handler.
16:       Click on the surface of the applet to start the animation.
17:    */
18:    public SelectionSortApplet()
19:    {
20:       class MousePressListener extends MouseAdapter
21:       {
22:          public void mousePressed(MouseEvent event)
23:          {
24:             if (animation != null && animation.isAlive()) 
25:                animation.interrupt();
26:             startAnimation();
27:          }
28:       }
29: 
30:       MouseListener listener = new MousePressListener();
31:       addMouseListener(listener);
32:       setBackground(Color.lightGray);
33: 
34:       sorter = null;
35:       animation = null;
36:    }
37: 
38:    public void paint(Graphics g)
39:    {
40:       if (sorter == null) return;
41:       Graphics2D g2 = (Graphics2D)g;
42:       sorter.draw(g2);
43:    }
44: 
45:    /**
46:       Starts a new animation thread.
47:    */
48:    public void startAnimation()
49:    {
50:       class AnimationThread extends Thread
51:       {
52:          public void run()
53:          {
54:             try
55:             {
56:                sorter.sort();
57:             }
58:             catch (InterruptedException exception)
59:             {
60:             }
61:          }
62:       }
63:       
64:       int[] values = ArrayUtil.randomIntArray(30, 300);
65:       sorter = new SelectionSorter(values, this);
66:       animation = new AnimationThread();
67:       animation.start();
68:    }
69: 
70:    private SelectionSorter sorter;
71:    private Thread animation;
72: }
73: