The main goal of Lab 8 is to enhance the students' understanding of applets.
Here is the Ball class:
import java.applet.*; import java.awt.*; import java.awt.event.*; // Ball.html will contain: applet code = Ball.class width = 500 height=500 /applet, // with the appropriate angled brackets public class Ball extends Applet implements Runnable, ActionListener { int x = 250, y = 250, r=30; // Position and radius of the circle int dx = 8, dy = 5; // Trajectory of circle Dimension size; // The size of the applet Graphics g; // A Graphics object for the buffer Thread animator = null; // Thread that performs the animation Button start; public void init() { size = this.size(); g = getGraphics(); start = new Button("start"); add(start); start.addActionListener(this); } public void paint(Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, size.width, size.height); // clear the buffer g = getGraphics(); g.setColor(Color.blue); g.fillOval(x-r, y-r, r*2, r*2); // draw the circle } public void update(Graphics g) { paint(g); } /** The body of the animation thread */ public void run() { while(true) { // Bounce the circle if we've hit an edge. if ((x - r + dx < 0) || (x + r + dx > size.width)) dx = -dx; if ((y - r + dy < 0) || (y + r + dy > size.height)) dy = -dy; // Move the circle. x += dx; y += dy; // Ask the browser to call our paint() method to redraw the circle // at its new position. Tell repaint what portion of the applet needs // be redrawn: the rectangle containing the old circle and the // the rectangle containing the new circle. These two redraw requests // will be merged into a single call to paint() repaint(x-r-dx, y-r-dy, 2*r, 2*r); // repaint old position of circle repaint(x-r, y-r, 2*r, 2*r); // repaint new position of circle // Now pause 50 milliseconds before drawing the circle again. try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } public void actionPerformed(ActionEvent e) { if(animator==null) { animator = new Thread(this); animator.start(); } } }