/** * Rebound.java * * Demonstrates an animation and the use of the Timer class. * @author Lewis and Loftus. Converted to JApplet by Scot Drysdale */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Rebound extends JApplet { private static final long serialVersionUID = 1L; private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 100; private final int IMAGE_SIZE = 35; private final int DELAY = 20; private Timer timer; // Timer object to get regular callbacks private Image image; // Image of thing to be drawn private int x, y, moveX, moveY; // /** * Sets up the applet, including the timer for the animation. */ public void init() { addMouseListener(new ReboundMouseListener()); Container cp = getContentPane(); // Content pane holds components cp.add(new Canvas()); // The canvas is the only component x = 0; y = 40; moveX = moveY = 3; image = getImage(getCodeBase(), "happyFace.gif"); setBackground(Color.black); setSize(APPLET_WIDTH, APPLET_HEIGHT); timer = new Timer(DELAY, new ReboundActionListener()); timer.start(); setVisible(true); // Makes the applet (and its components) visible } private class Canvas extends JPanel { private static final long serialVersionUID = 1L; /** * Draws the image in the current location. * @param page the graphics object to draw on. */ public void paintComponent(Graphics page) { super.paintComponent(page); page.drawImage(image, x, y, this); } } /** * Represents the mouse listener for the applet. */ private class ReboundMouseListener implements MouseListener { /** * Stops or starts the timer (and therefore the animation) * when the mouse button is clicked. * @param event the event that caused this callback */ public void mouseClicked(MouseEvent event) { if (timer.isRunning()) timer.stop(); else timer.start(); } //-------------------------------------------------------------- // Provide empty definitions for unused event methods. //-------------------------------------------------------------- public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mousePressed(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} } /** * Represents the action listener for the timer. */ private class ReboundActionListener implements ActionListener { /** * Updates the position of the image and possibly the direction * of movement whenever the timer fires an action event. * @param event the event that caused this callback */ public void actionPerformed(ActionEvent event) { x += moveX; y += moveY; if (x <= 0 || x >= APPLET_WIDTH - IMAGE_SIZE) moveX = moveX * -1; if (y <= 0 || y >= APPLET_HEIGHT - IMAGE_SIZE) moveY = moveY * -1; repaint(); } } }