GUI PROGRAMMING 107
3.8. GUI PROGRAMMING 107
The applet first fills its entire rectangular area with red. Then it changes the drawing color to black and draws a sequence of rectangles, where each rectangle is nested inside the previous one. The rectangles can be drawn with a while loop. Each time through the loop, the rectangle gets smaller and it moves down and over a bit. We’ll need variables to hold the width and height of the rectangle and a variable to record how far the top-left corner of the rectangle is inset from the edges of the applet. The while loop ends when the rectangle shrinks to nothing. In general outline, the algorithm for drawing the applet is
Set the drawing color to red (using the g.setColor subroutine) Fill in the entire applet (using the g.fillRect subroutine) Set the drawing color to black Set the top-left corner inset to be 0 Set the rectangle width and height to be as big as the applet while the width and height are greater than zero:
draw a rectangle (using the g.drawRect subroutine) increase the inset decrease the width and the height
In my applet, each rectangle is 15 pixels away from the rectangle that surrounds it, so the inset is increased by 15 each time through the while loop. The rectangle shrinks by 15 pixels on the left and by 15 pixels on the right, so the width of the rectangle shrinks by 30 each time through the loop. The height also shrinks by 30 pixels each time through the loop.
It is not hard to code this algorithm into Java and use it to define the paint() method of an applet. I’ve assumed that the applet has a height of 160 pixels and a width of 300 pixels. The size is actually set in the source code of the Web page where the applet appears. In order for an applet to appear on a page, the source code for the page must include a command that specifies which applet to run and how big it should be. (We’ll see how to do that later.) It’s not a great idea to assume that we know how big the applet is going to be. On the other hand, it’s also not a great idea to write an applet that does nothing but draw a static picture. I’ll address both these issues before the end of this section. But for now, here is the source code for the applet:
import java.awt.*; import java.applet.Applet;
public class StaticRects extends Applet { public void paint(Graphics g) { // Draw a set of nested black rectangles on a red background.
// Each nested rectangle is separated by 15 pixels on // all sides from the rectangle that encloses it.
int inset;
// Gap between borders of applet //
and one of the rectangles.
int rectWidth, rectHeight; // The size of one of the rectangles. g.setColor(Color.red);
g.fillRect(0,0,300,160); // Fill the entire applet with red. g.setColor(Color.black); // Draw the rectangles in black. inset = 0; rectWidth = 299;
// Set size of first rect to size of applet.