您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)

 

Content Index

Content Page # 22

The "BallWorld" class - version 6

Although successful, for version 5 of our bouncing ball application we had to duplicate a lot of lines to make each of the balls bounce. Therefore for version 6, we will not change the behaviour of our software, but we will see how we can reduce duplicated code by creating a new method in our BallWorld application.

We shall now create a new BallWorld method called "bounce". This method will require an argument that is a reference to some Ball object, and the method will check the X and Y position of the object, and change the object's motion in just the same way we have written in our "paint" method. With such a "bounce" method we can remove all the duplicated code from our "paint" method, and just call our "bounce" method once for each ball.

The new method will look as follows:

  • private void bounce(Ball ball)

    {

    // check for left of frame collision (X value too small)

    if ( ball.getX() < 0 )

    ball.setMotion( -ball.getXMotion(), ball.getYMotion() );

    // check for right of frame collision (X value too large)

    if ( ball.getX() > frameWidth )

    ball.setMotion(-ball.getXMotion(), ball.getYMotion());

    // check for top of frame collision (Y value too small)

    if ( ball.getY() < 0 ) 

    ball.setMotion(ball.getXMotion(), -ball.getYMotion());

    // check for bottom of frame collision (Y value too large)

    if ( ball.getY() > frameHeight )

    ball.setMotion(ball.getXMotion(), -ball.getYMotion());

    }

  • As can be see form the above, apart from calling the object reference "ball", the code is just the same as before. When this "bounce" method is called, the "ball" reference will be made to the same object as provided in the argument - so "bounce( myBall )" will mean that "ball" refers to the same object as "myBall". When called with "bounce( anotherBall )" then "ball" will refer to the same object as "anotherBall".

    Our "paint" method can now be simplified to the following:

  • public void paint(Graphics g)

    {

    myBall.paint(g);

    myBall.move();

    anotherBall.paint(g);

    anotherBall.move();

    pause( 20 );

    // NEW NEW NEW - call method "bounce" with each ball reference

    bounce( myBall );

    bounce( anotherBall );

    counter = counter + 1;

    if (counter < 500) 

    repaint();

    else 

    System.exit(0);

    }

  • The full source file is available for viewing: BallWorld.java - version 6  

    Perform activity 7 – Compilation and running of "BallWorld.java" - version 6

    Back to top

    basicline.gif (169 bytes)

    RITSEC - Global Campus
    Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
    webmaster@globalcampus.com.eg