2016-03-20 87 views
2

這段代碼只讓球繼續前進,我怎麼能讓球返回?讓球返回小程序

我可以將它添加到循環中以使球返回到左側的表達式是什麼。

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

爲了更好地幫助更快,發佈[MCVE]或[短的,獨立的,正確示例](http://www.sscce.org/)。 –

回答

1

當球在窗口的右邊,你想將其帶到0.50我相信。只需做相反的步驟,你可以把它帶到右邊。

X統籌設置爲右邊緣(儘量不要做X,Y,直徑,顏色,最終)和重新實例對象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 

我想這會工作得很好:)