1 /* 2 * Assignment 4 Problem 8: Stella 3 * The number of concentric squares will be read from a dialog box. 4 * Two randomly chosen colors will be used for the image that is painted when the program is run. 5 * The canvas will be of size 800 by 800 and the largest square will be 700 by 700. 6 */ 7 8 package npw; 9 10 import painter.SPainter; 11 import shapes.SSquare; 12 import javax.swing.*; 13 import java.awt.*; 14 import java.util.Random; 15 import java.util.Scanner; 16 17 18 public class Stella { 19 public static void main(String[] args){ 20 SwingUtilities.invokeLater(new Runnable() { 21 public void run() { 22 new Stella(); 23 } 24 }); 25 } 26 public Stella() { 27 paintTheImage(); 28 } 29 30 private void paintTheImage() { 31 SPainter painter = new SPainter("Stella",800,800); 32 SSquare square = new SSquare(700); 33 int squareNum = getNumber("Number of concentric squares"); 34 // the side is to make sure the squares are spaced equal length 35 double side = square.side()/(squareNum+1); 36 // to make sure there is only two random color, create random color 37 Color color1 = randomColor(); 38 Color color2 = randomColor(); 39 int i = 0; 40 while (i <= squareNum){ 41 // use odd and even so that the square wont be paint twice with same color. 42 if (i % 2 == 0) { 43 painter.setColor(color1); 44 painter.paint(square); 45 square.shrink(side); 46 } else { 47 painter.setColor(color2); 48 painter.paint(square); 49 square.shrink(side); 50 } 51 i++; 52 } 53 } 54 55 private static int getNumber(String prompt) { 56 // The input from the Input Dialog is a string so need to scanner to make sure it's a int. 57 String nss = JOptionPane.showInputDialog(null, prompt + "?"); 58 Scanner scanner = new Scanner(nss); 59 return scanner.nextInt(); 60 } 61 62 private static Color randomColor() { 63 Random rgen = new Random(); 64 int r = rgen.nextInt(256); 65 int g = rgen.nextInt(256); 66 int b = rgen.nextInt(256); 67 return new Color (r,g,b); 68 } 69 } 70