Appendix F. Hints and Solutions to Exercises

1.1 Numbers of pixels:

g.drawLine (10, 20, 100, 50); // 100 - 10 + 1 = 91 pixels
g.drawRect (10, 10, 8, 5);    // 2 * 8 + 2 * 5 = 26 pixels
g.fillRect (10, 10, 8, 5);    // 8 * 5 = 40 pixels

1.2 Program to draw many squares:

// ManySq.java: This program draws n x n sets, each
//   consisting of k squares, arranged as on a chessboard.
//   Each edge is divided into two parts with ratio
//   (1 - q)  : q. The values of n, k and q are program
              arguments.

import java.awt.*;
import java.awt.event.*;

public class ManySq extends Frame
{  public static void main(String[] args)
   {  if (args.length != 3)
      {  System.out.println("Supply n, k and q as arguments");
         System.exit(1);
} int n = Integer.valueOf(args[0]).intValue(), k = Integer.valueOf(args[1]).intValue(); float q = Float.valueOf(args[2]).floatValue(); new ManySq(n, k, q); } ManySq(int n, int k, float q) { super("ManySq: Many squares"); addWindowListener(new WindowAdapter() {public void windowClosing( WindowEvent e){System.exit(0);}}); add("Center", new CvManySq(n, k, q)); setSize (600, 400); show(); } } class CvManySq extends Canvas { int centerX, centerY, n, k; float p0, q0; CvManySq(int nn, int kk, float qq){n=nn; k=kk; q0=qq; p0 = 1-q0;} int iX(float x){return Math.round(centerX + x);} int iY(float y){return Math.round(centerY - y);} public void paint(Graphics g) { Dimension d = getSize(); int maxX = d.width - 1, maxY = d.height - 1, minMaxXY = Math.min(maxX, maxY); centerX = maxX/2; centerY = maxY/2; float ...

Get Computer Graphics for Java Programmers, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.