这段代码只让球前进,如何让球返回?
我可以将它添加到循环中以使球返回到左侧的表达式是什么。
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、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
我想这会工作得很好:)
关于java - 让球返回小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36114469/