Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import javax.swing.*;
- public class MovingBall extends JPanel {
- Ball ball = new Ball();
- void startAnimation() {
- while( true ) {
- try {
- Thread.sleep( 25 );
- ball.go();
- repaint();
- } catch( InterruptedException e ) {}
- } // end while( true )
- } // end method startAnimation()
- protected void paintComponent( Graphics g ) {
- super.paintComponent( g );
- ball.draw( g );
- } // end method paintComponent
- class Ball {
- int x;
- int y;
- int xSpeed = 100;
- int ySpeed = 70;
- void go() {
- x = x + (xSpeed*25)/1000;
- y = y + (ySpeed*25)/1000;
- if( x < 0 ) {
- x = 0;
- xSpeed = -xSpeed;
- } else if( x > 490 ) {
- x = 490;
- xSpeed = -xSpeed;
- } else if( y < 0 ) {
- y = 0;
- ySpeed = -ySpeed;
- } else if( y > 490 ) {
- y = 490;
- ySpeed = -ySpeed;
- } // end if-else block
- } // end method go()
- void draw( Graphics g ) {
- g.fillOval( x , y , 10 , 10 );
- } // end method draw
- } // end inner class Ball
- public static void main( String[] args ) {
- JFrame window = new JFrame();
- window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
- MovingBall animation = new MovingBall();
- animation.setPreferredSize( new Dimension( 500 , 500 ) );
- animation.setBackground( Color.white );
- window.add( animation );
- window.pack();
- window.setVisible( true );
- animation.startAnimation();
- } // end method main
- } // end class MovingBall
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement