moonlight
moonlight

Reputation: 37

Making the ball returns back in applet

This code makes the ball go forward only , how i can make the ball returns back?

what is the expression that i can add it to the loop in order to make the ball returns back to the left.

Applet Viewer

    public class NewJApplet extends JApplet {    
        public void paint(Graphics g) 
        {
            final int X=0;
            final int Y=50;
            final int DIAMETER=15;
            final Color COLOR= Color.BLACK;
            final int SPACE =5;
            // instantiate the ball as a Circle object
            Circle baall = new Circle(X,Y,DIAMETER,COLOR); 

 // get ball diameter and width & height of the applet window
            int ballDiam = baall.getDiameter();
            int windWidth= getWidth();
            int windHeight=getHeight();

// rolling horizontally
    // check whether ball is at right edge of window   
            while(baall.getX()+ballDiam<windWidth)
            {
                baall.draw(g);

                try {
                        Thread.sleep(50);
                    } catch (Exception e) {
                        System.out.println("There is an error in sleep ! ");
                }
// clear the window
                g.clearRect(0, 0, windWidth, windHeight);
// position to next location for drawing ball
                baall.setX(baall.getX()+SPACE);

            }
            baall.draw(g); // draw the ball in the current position
        }
    }

Upvotes: 2

Views: 76

Answers (1)

user5794376
user5794376

Reputation:

When the ball is at the right edge of the window, you want to bring it to 0,50 I presume. Simply do the opposite of the steps you do to take it to the right edge.

• Setting X co-ordinate to right edge (try not making X, Y, DIAMETER, COLOR as final) and reinstantiating Circle object baall

X = getWidth()-15;
baall=new Circle(X,Y,DIAMETER,COLOR);

• Checking if the ball is at left edge and drawing it.

while(baall.getX()-ballDiam>0) { 
    baall.draw(g); 
    try { 
        Thread.sleep(50); }
    catch(Exception e){ 
        System.out.println("There is an error in sleep ! "); 
    }

• Clearing window and positioning next location

g.clearRect(0, 0, windWidth, windHeight);
baall.setX(baall.getX()-SPACE);
} //while

I guess this'll work just fine :)

Upvotes: 1

Related Questions