CS 100: Lecture L6
February 11
Filling in a Semicircle: A For-loop graphics example
// L6A A solid semicircle. import java.io.*; import java.awt.*; public class CUCSDrawing extends Frame { final int r = 250; // The radius of the semicircle final int xc = 400; final int yc = 300; // The center of the semicircle = (xc,yc). public void paint(Graphics g) { // We'll draw a magenta semicircle with the "dome" on top by drawing every possible // vertical line segment that is inside the semicircle. g.setColor(Color.magenta); int x; // The horizontal coordinate of the current "fill" line. int y; // Vertical coordinare of the "top" of the current fill line. for (x=xc-r;x<=xc+r;x=x+1) { y = (int) (yc - Math.sqrt(Math.pow(r,2)-Math.pow(x-xc,2))); g.drawLine(x,yc,x,y); } } } public class L6A { public static void main(String args[]) { CUCSDrawing d = new CUCSDrawing(); d.resize(900,750); // Modify as appropriate. d.move(0,75); d.setTitle("Drawing"); // Modify as appropriate. d.show(); d.toFront(); } }
Drawing a Grid
// L6B: An n-by-n grid with a disk on the center tile assuming n is odd. import java.io.*; import java.awt.*; public class CUCSDrawing extends Frame { final int left = 100; // Horizontal coordinate of the board's left edge. final int top = 100; // Vertical coordinate of the board's top edge. final int n = 9; // The board size. (The board will be n-by-n). final int s = 50; // Gridlines are spaced this far apart. public void paint(Graphics g) { int k; // Gridline ndex int v = top; // Vertical coordinate of the kth horizontal gridline. int h = left; // Horizontal coordinate of the kth vertical gridline. int right = left+n*s; // Horizontal coordinate of the board's right edge. int bottom = top+n*s; // Vertical coordinate of the board's bottom edge. for (k=1;k<=n+1;k=k+1) { // Draw the kth horizontal gridline and the kth vertical gridline. g.drawLine(left,v,right,v); g.drawLine(h,top,h,bottom); h = h+s; v = v+s; } // Now place the disk on the center tile. // The upper left corner of the center tile is over m*s and down m*s // from the upper left corner of the grid where m = n/2 in // integer arithmetic. int m = n/2; g.setColor(Color.magenta); g.fillOval(left+m*s,top+m*s,s,s); } } public class L6B { public static void main(String args[]) { CUCSDrawing d = new CUCSDrawing(); d.resize(900,750); d.move(0,75); d.setTitle("A Grid"); d.show(); d.toFront(); } }