此代码仅使球前进,我如何使球返回?

我可以将其添加到循环中的表达式是什么,以便使球返回到左侧。

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
        }
    }

最佳答案

当球在窗口的右边缘时,您想将其调到0,50我想。只需执行与步骤相反的步骤即可将其移至右侧。

•将X坐标设置为右边缘(尝试不使X,Y,直径,颜色为最终值),并重新实例化Circle对象栏

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


•检查球是否在左边缘并进行绘制。

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


•清除窗口并定位下一个位置

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


我想这会很好:)

10-05 18:27