/** We must import the Graphics classes from uwcse.jar for this
* example. If Dr. Java cannot find this package,
select the
* Edit>Preferences menu item, and press the Add button
to add
* the .jar to the ClassPath. After pressing the Add
button just
* navigate to and select the uwcse.jar file, wherever it is
on
* your computer.
*/
import uwcse.graphics.*;
import java.awt.Color;
/** A class just to wrap the looping functionality we are
demonstrating.
*/
public class LoopTest {
/** The graphics window is an instance variable, for
persistence.
*/
GWindow gw;
/** Constructor initializes the window.
*/
public LoopTest() {
gw = new GWindow();
}
/** Endlessly running method to move a rectangle back and
forth
*/
public void run() {
// rect is local to this method. Create
it and add it to the window
Rectangle rect = new Rectangle();
gw.add(rect);
int i = 0;
while ( true ) { //i.e. do this outer loop
forever.
rect.setColor(Color.red); //static
constants defined in class Color
while ( i < 250) { //nested
inner loop to move to the right
rect.moveTo(rect.getX() + 1,
rect.getY());
i = i + 1;
}
rect.setColor(Color.green);
while ( i > 20 ) {
//nested inner loop to move to the left
rect.moveTo(rect.getX() - 1, rect.getY());
i = i - 1;
}
}
}
/** Draw a shaded stripe across and down.
Demonstrate for-loop construct.
*/
public void oneShot() {
for (int i = 10; i < 250; i++)
{ //standard for loop structure.
Rectangle newRect = new
Rectangle(); //NOTE: new Rectangle
created EVERY ITERATION temporarily help in local var
Color newColor = new
Color(i, i/2, 200); //NOTE: same goes for this new Color
newRect.setColor(newColor);
gw.add(newRect);
newRect.moveTo(2*i, i);
}
// Local variables have vanished by
this point.
// Rectangles stay on the screen
because they are referenced by gw, which persists.
}
}