|
ColorfulAbstractGradient.java
|
1 /*
2 * A program to paint a colorful abstract gradient in the vertical direction.
3 */
4
5 package npw;
6
7 import painter.SPainter;
8 import shapes.SCircle;
9
10 import javax.swing.*;
11 import java.awt.*;
12 import java.util.Random;
13 import java.util.Scanner;
14
15 public class ColorfulAbstractGradient {
16
17 public static void main(String[] args) {
18 SwingUtilities.invokeLater(ColorfulAbstractGradient::new);
19 }
20
21 public ColorfulAbstractGradient() {
22 paintTheImage();
23 }
24
25 private void paintTheImage(){
26 // Grab the input information
27 int width = getNumber("width");
28 int height = getNumber("height");
29 int colWidth = getNumber("column width");
30 // Establish the painter
31 SPainter painter = new SPainter("Colorful Abstract Gradient", width, height);
32 SCircle dot = new SCircle(5);
33
34 // Move the painter to the upper left corner to get ready to paint the gradient
35 painter.mfd(height/2);
36 painter.tl(90);
37 painter.mfd(width/2 -10);
38 painter.tl(90);
39
40 // Paint it!
41 paintGradient(painter, dot, height, width, colWidth);
42 }
43
44 private static int getNumber(String prompt) {
45 String nss = JOptionPane.showInputDialog(null,prompt+"?");
46 Scanner scanner = new Scanner(nss);
47 return scanner.nextInt();
48 }
49
50 private void paintGradient(SPainter painter, SCircle dot, int height, int width, int colWidth){
51 int cols = 0;
52 // Calculate the number of columns.
53 int nrOfCols = ( width / colWidth - 2);
54
55 while (cols < nrOfCols){
56 nextCol(painter, colWidth);
57 paintColumn(painter, dot, height);
58 cols = cols + 1;
59 }
60 }
61
62 private void paintOneDot(SPainter painter, SCircle dot){
63 randomColor(painter);
64 painter.paint(dot);
65 }
66
67 // Dots are spaced tighter together near the bottom of the canvas.
68 private void paintColumn(SPainter painter, SCircle dot, int height) {
69 int travel = 0;
70 int totalDistanceTraveled = 0;
71
72 // Paint a row with decreasing distance between dots.
73 while(totalDistanceTraveled < height - (dot.radius() * 3)) {
74 travel = randomDistance((height - totalDistanceTraveled) / 4);
75 totalDistanceTraveled = totalDistanceTraveled + travel;
76 painter.mfd(travel);
77 paintOneDot(painter, dot);
78 }
79
80 // Make the method invariant with respect to painter position.
81 painter.mbk(totalDistanceTraveled);
82 }
83
84 // Moves the painter to the next column.
85 private void nextCol(SPainter painter, int colWidth){
86 painter.tl(90);
87 painter.mfd(colWidth);
88 painter.tr(90);
89 }
90
91 private int randomDistance(int maxDistance){
92 Random rgen = new Random();
93 return rgen.nextInt(maxDistance);
94 }
95
96 private void randomColor(SPainter painter) {
97 Random colorful = new Random();
98 int r = colorful.nextInt(255);
99 int g = colorful.nextInt(255);
100 int b = colorful.nextInt(255);
101 painter.setColor(new Color(r,g,b));
102 }
103 }
104