1. /**
  2. * Draws a ball bouncing around
  3. */
  4. import java.applet.*;
  5. import java.awt.*;
  6. import javax.swing.*;
  7. public class ball extends Applet implements Runnable {
  8. int x_pos = 10;
  9. int y_pos = 100;
  10. int radius = 20;
  11. private Image image;
  12. private Graphics graphic;
  13. public void init() {
  14. setBackground(Color.blue);
  15. }
  16. public void start() {
  17. Thread th = new Thread( /* this*/this);
  18. th.start();
  19. }
  20. public void stop() {
  21. }
  22. public void destroy() {
  23. }
  24. public void run() {
  25. Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  26. while ( true ) {
  27. x_pos++;
  28. repaint();
  29. try {
  30. Thread.sleep(20);
  31. }
  32. catch (InterruptedException ie) {
  33. }
  34. Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
  35. }
  36. }
  37. public void paint(Graphics g) {
  38. g.setColor(Color.red);
  39. g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
  40. }
  41. public void update(Graphics g) {
  42. // initialize buffer
  43. if ( image == null ) {
  44. image = createImage(this.getSize().width, this.getSize().height);
  45. graphic = image.getGraphics();
  46. }
  47. // clear screen in background
  48. graphic.setColor(getBackground());
  49. graphic.fillRect(0, 0, this.getSize().width, this.getSize().height);
  50. // draw elements in background
  51. graphic.setColor(getForeground());
  52. paint(graphic);
  53. // draw image on the screen
  54. g.drawImage(image, 0, 0, this);
  55. }
  56. }