让球在小程序中返回

时间:2016-03-20 13:40:42

标签: java swing applet awt java-2d

这段代码只让球前进,我怎样才能让球返回?

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

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

1 个答案:

答案 0 :(得分:1)

当球位于窗口的右边缘时,你想把它带到 0,50 我猜想。只需执行相反的步骤即可将其带到右边缘。

•将 X 坐标设置为右边缘(尽量不要将X,Y,DIAMETER,COLOR设为最终)并重新实现 Circle 对象 baall

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

我想这样可以正常工作:)