import javabook.*; import java.awt.*; /** * DrawingLab3 * Inspired by a lab from Jeff Ondich * @author Dave Musicant * @version 2.0 12/20/01 * * 0. Compile it, run it, and figure out how it works. * * 1. Complain about the flickering. * * 2. To slow the motion down or speed it up, change the argument * to Thread.sleep() (measured in milliseconds). * * 3. Try to get the box to bounce from side to side instead of up * and down. * * 4. Modify your program so that your box doesn't go behind the borders * or the titlebar. * * 5. Can you get the colors to change gradually from red to blue * instead of abruptly? Remember, you can define colors with * the right arguments to "new Color()". */ class DrawingLab3 extends MainWindow { // Data values final private int windowWidth = 600; final private int windowHeight = 600; private int positionX; private int positionY; private int squareSize; private Color squareColor; private Color currentColor; private Color backgroundColor; private boolean goingUp; public DrawingLab3() { setVisible(true); toFront(); setSize(windowWidth,windowHeight); backgroundColor = Color.white; setBackground(backgroundColor); squareSize = 50; positionX = windowWidth / 2; positionY = windowHeight / 2; goingUp = true; squareColor = Color.blue; } public void paint(Graphics graphics) { graphics.setColor(currentColor); graphics.drawRect(positionX,positionY,squareSize,squareSize); } public void animate() { // Do the animation. This is an intentionally infinite loop. while(true) { // Draw the square currentColor = squareColor; repaint(); // Wait a while. If Thread.sleep throws an EXCEPTION, // catch the exception and ignore it. try { Thread.sleep(10); } catch (InterruptedException e) { } // Erase the square currentColor = backgroundColor; repaint(); // Move the square newCenter(); } } private void newCenter() { if (goingUp) positionY = positionY - 1; else positionY = positionY + 1; if (positionY >= windowHeight - squareSize) { goingUp = true; squareColor = Color.blue; } else if (positionY <= 0) { goingUp = false; squareColor = Color.red; } } public static void main(String[] args) { DrawingLab3 dw = new DrawingLab3(); dw.animate(); } }