1 /* 2 * Invention 2 Uses a while and if statement to draw a different image each time using only rectangles 3 */ 4 5 6 package npw; 7 import java.awt.Color; 8 import java.util.Random; 9 import javax.swing.SwingUtilities; 10 import painter.SPainter; 11 import shapes.SCircle; 12 import shapes.SRectangle; 13 import shapes.SSquare; 14 public class Invention2 { 15 // REQUIRED INFRASTRUCTURE 16 public Invention2() { 17 paintTheImage(); 18 } 19 20 21 // THE PAINTER DOING ITS THING 22 private void paintTheImage() { 23 SPainter painter = new SPainter("Invention2", 600, 600); 24 paintBackground(painter); 25 int nrOfRect = 4; 26 paintRectangles(painter, nrOfRect); 27 } 28 29 private void paintBackground(SPainter painter) { 30 painter.setColor(Color.BLACK); 31 SSquare back = new SSquare(2000); 32 painter.paint(back); 33 } 34 35 private void paintRectangles(SPainter painter, int nrOfRect) { 36 37 int i = 1; 38 while (i <= nrOfRect) { 39 paintOneRect(painter); 40 i = i + 1; 41 } 42 } 43 44 private static Color randomColor() { 45 Random rgen = new Random(); 46 int r = rgen.nextInt(256); 47 int g = rgen.nextInt(256); 48 int b = rgen.nextInt(256); 49 return new Color ( r, g , b); 50 51 52 } 53 54 private void paintOneRect(SPainter painter) { 55 Color color1 = randomColor(); 56 Color color2 = randomColor(); 57 Random rgen = new Random(); 58 int rn = rgen.nextInt(3); 59 if (rn == 0) { ///Generates random colors for 3/4 of rectangles 60 painter.setColor(color1); 61 } else if (rn == 1) { 62 painter.setColor(color2); 63 } else 64 painter.setColor(new Color(255, 255, 23)); 65 66 67 int rectH = 50; 68 int rectW = 20; 69 SRectangle rectangle = new SRectangle(rectH,rectW); 70 painter.mfd(rectangle.height()); 71 painter.tr(); 72 painter.paint(rectangle); 73 painter.setColor(Color.BLACK); 74 painter.draw(rectangle); 75 } 76 public static void main(String[] args) { 77 SwingUtilities.invokeLater(new Runnable() { 78 public void run() { 79 new Invention2(); 80 } 81 }); 82 } 83 } 84