Guest User

Untitled

a guest
Jul 22nd, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. /**
  2. *
  3. */
  4. package example10;
  5.  
  6. import java.awt.Color;
  7. import java.awt.Graphics;
  8. import javax.swing.JApplet;
  9.  
  10. /**
  11. * @author pajensen
  12. *
  13. */
  14. public class BouncingBall extends JApplet implements Runnable
  15. {
  16. // Object variables
  17. double x, y;
  18. double xVelocity, yVelocity;
  19.  
  20. public void init ()
  21. {
  22. x = 50;
  23. y = 0;
  24. xVelocity = 1;
  25. yVelocity = 0;
  26.  
  27. // Begin a new thread of execution.
  28.  
  29. Thread otherExecutionThread;
  30. otherExecutionThread = new Thread (this);
  31. otherExecutionThread.start();
  32.  
  33. // At this point, the old thread is still running,
  34. // but a new thread has started.
  35.  
  36. System.out.println ("The old thread is still running.");
  37. }
  38.  
  39. public void paint(Graphics g)
  40. {
  41. // Clear background
  42.  
  43. g.setColor(Color.BLUE.darker());
  44. g.fillRect(0, 0, getWidth(), getHeight());
  45.  
  46. // Draw a ball.
  47.  
  48. g.setColor(Color.YELLOW);
  49. g.fillOval((int)x, (int)y, 40, 40);
  50. g.setColor(Color.GREEN);
  51. g.fillArc((int)x+20, (int)y+10, 10, 10, 45, 45);
  52. }
  53.  
  54. public void run ()
  55. {
  56. System.out.println ("The other thread has started.");
  57.  
  58. while(true)
  59. {
  60. try
  61. {
  62. Thread.sleep(20); // Fifty times a second.
  63. }
  64. catch(Exception e) {}
  65. y = y + yVelocity;
  66. x = x + xVelocity;
  67.  
  68. if (y > this.getHeight()-40)
  69. yVelocity = -(Math.abs(yVelocity));
  70. else
  71. yVelocity += 0.1; // Fixed after class, used to be before the if statement
  72.  
  73. if (x > this.getWidth()-40)
  74. xVelocity = -(Math.abs(xVelocity));
  75.  
  76. if (x < 0)
  77. xVelocity = +(Math.abs(xVelocity));
  78.  
  79. repaint();
  80. }
  81.  
  82.  
  83. }
  84.  
  85. }
Add Comment
Please, Sign In to add comment