Advertisement
Guest User

Untitled

a guest
Dec 6th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. import java.awt.*;
  2. import javax.swing.*;
  3.  
  4. public class MovingBall extends JPanel {
  5. Ball ball = new Ball();
  6.  
  7. void startAnimation() {
  8. while( true ) {
  9. try {
  10. Thread.sleep( 25 );
  11. ball.go();
  12. repaint();
  13. } catch( InterruptedException e ) {}
  14. } // end while( true )
  15. } // end method startAnimation()
  16.  
  17. protected void paintComponent( Graphics g ) {
  18. super.paintComponent( g );
  19. ball.draw( g );
  20. } // end method paintComponent
  21.  
  22.  
  23. class Ball {
  24. int x;
  25. int y;
  26. int xSpeed = 100;
  27. int ySpeed = 70;
  28.  
  29. void go() {
  30. x = x + (xSpeed*25)/1000;
  31. y = y + (ySpeed*25)/1000;
  32. if( x < 0 ) {
  33. x = 0;
  34. xSpeed = -xSpeed;
  35. } else if( x > 490 ) {
  36. x = 490;
  37. xSpeed = -xSpeed;
  38. } else if( y < 0 ) {
  39. y = 0;
  40. ySpeed = -ySpeed;
  41. } else if( y > 490 ) {
  42. y = 490;
  43. ySpeed = -ySpeed;
  44. } // end if-else block
  45. } // end method go()
  46.  
  47. void draw( Graphics g ) {
  48. g.fillOval( x , y , 10 , 10 );
  49. } // end method draw
  50. } // end inner class Ball
  51.  
  52.  
  53. public static void main( String[] args ) {
  54. JFrame window = new JFrame();
  55. window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  56. MovingBall animation = new MovingBall();
  57. animation.setPreferredSize( new Dimension( 500 , 500 ) );
  58. animation.setBackground( Color.white );
  59. window.add( animation );
  60. window.pack();
  61. window.setVisible( true );
  62.  
  63. animation.startAnimation();
  64. } // end method main
  65. } // end class MovingBall
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement