import javabook.*; import java.awt.*; import java.awt.event.*; /** * Simple animation that demonstrates how to pause the * animation while an OutputBox is visible. Take a look * at the variable "paused" in animate() and mousePressed(). * Also note the use of waitUntilClose() in mousePressed(). * * @author Jeff Ondich * @version 3/13/03 */ class Pauser extends MainWindow implements MouseListener { // 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; private boolean paused; public static void main(String[] args) { Pauser dw = new Pauser(); dw.animate(); } public Pauser() { addMouseListener( this ); setVisible(true); toFront(); setSize(windowWidth,windowHeight); backgroundColor = Color.white; setBackground(backgroundColor); squareSize = 50; positionX = windowWidth / 2; positionY = windowHeight / 2; goingUp = true; squareColor = Color.blue; paused = false; } 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 ) { if( !paused ) { // Erase the square currentColor = backgroundColor; repaint(); // Move the square newCenter(); // 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) { } } } } 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 void mousePressed( MouseEvent e ) { paused = true; OutputBox out = new OutputBox( this ); out.show(); out.printLine( "Hi" ); out.waitUntilClose(); paused = false; } public void mouseReleased( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } }