11package sortVisualiser ;
22
3+ import java .awt .Color ;
4+ import java .awt .Dimension ;
5+ import java .awt .Graphics ;
6+ import java .awt .Graphics2D ;
37import java .util .Random ;
8+ import javax .swing .JPanel ;
49import static util .Sleep .sleepFor ;
510
611/**
712 * The array that can be sorted
813 * @author mhops
914 */
10- public class SortArray {
11- private final ArrayCanvas arrayVisualiser ;
15+ public class SortArray extends JPanel {
16+ public static final int WIN_WIDTH = 1280 ;
17+ public static final int WIN_HEIGHT = 720 ;
18+ private static final int BAR_WIDTH = 8 ;
19+ private static final int NUM_BARS = WIN_WIDTH / BAR_WIDTH ;
1220 private int [] array ;
21+ private int [] accessColourMod ;
1322
14- public SortArray (int len , ArrayCanvas arrayVisualiser ) {
15- array = new int [len ];
16- for (int i = 0 ; i < len ; i ++) {
23+ public SortArray () {
24+ setBackground (Color .darkGray );
25+ array = new int [NUM_BARS ];
26+ accessColourMod = new int [NUM_BARS ];
27+ for (int i = 0 ; i < NUM_BARS ; i ++) {
1728 array [i ] = i ;
18- }
19- shuffleArray ();
20-
21- this .arrayVisualiser = arrayVisualiser ;
22- }
23-
24- private void shuffleArray () {
25- Random rng = new Random ();
26- for (int i = 0 ; i < array .length ; i ++) {
27- int swapWithIndex = rng .nextInt (array .length - 1 );
28- int temp = array [i ];
29- array [i ] = array [swapWithIndex ];
30- array [swapWithIndex ] = temp ;
29+ accessColourMod [i ] = 0 ;
3130 }
3231 }
3332
34- public int size () {
33+ public int arraySize () {
3534 return array .length ;
3635 }
3736
@@ -43,7 +42,50 @@ public void swapUpdate(int firstIndex, int secondIndex) {
4342 int temp = array [firstIndex ];
4443 array [firstIndex ] = array [secondIndex ];
4544 array [secondIndex ] = temp ;
46- arrayVisualiser .repaint ();
45+
46+ accessColourMod [firstIndex ] = 100 ;
47+ accessColourMod [secondIndex ] = 100 ;
48+ repaint ();
4749 sleepFor (10000 );
4850 }
51+
52+ /**
53+ * Gets the canvas size
54+ * @return size
55+ */
56+ @ Override
57+ public Dimension getPreferredSize () {
58+ return new Dimension (WIN_WIDTH , WIN_HEIGHT );
59+ }
60+
61+ public void resetColours () {
62+ for (int i = 0 ; i < NUM_BARS ; i ++) {
63+ accessColourMod [i ] = 0 ;
64+ }
65+ repaint ();
66+ }
67+
68+ /**
69+ * Draws the array
70+ * @param g The graphics device for drawing
71+ */
72+ @ Override
73+ public void paintComponent (Graphics g ) {
74+ Graphics2D graphics = (Graphics2D )g ;
75+ super .paintComponent (graphics );
76+
77+ graphics .setColor (Color .white );
78+ for (int x = 0 ; x < NUM_BARS ; x ++) {
79+ int height = getValue (x ) * 3 ;
80+ int xBegin = x + (BAR_WIDTH - 1 ) * x ;
81+ int yBegin = WIN_HEIGHT - height ;
82+
83+ int val = accessColourMod [x ] * 2 ;
84+ graphics .setColor (new Color (255 , 255 - val , 255 - val ));
85+ graphics .fillRect (xBegin , yBegin , BAR_WIDTH , height );
86+ if (accessColourMod [x ] > 0 ) {
87+ accessColourMod [x ]-= 5 ;
88+ }
89+ }
90+ }
4991}
0 commit comments