BouncingBallThread
Retired DISLab
BouncingBallThread.java
import acm.program.*; public class BouncingBallUsingThread extends GraphicsProgram { /** Initialize the ball and its velocity components */ public void init() { ball = new RunnableGBall(BALL_RADIUS); ball.setEnclosureSize(getWidth(), getHeight()); ball.setVelocity(2, 1); add(ball, getWidth() / 2, getHeight() /2 ); } /** Create a thread to bounce the ball */ public void run() { waitForClick(); new Thread(ball).start(); } /* Private constants */ private static final double BALL_RADIUS = 10; /* Private instance variables */ private RunnableGBall ball; private static final long serialVersionUID = 1; }
RunnableGBall.java
- 이 부분의 본문은 RunnableGBall입니다.
public class RunnableGBall extends GBall implements Runnable { /** Creates a new ball with radius r centered at the origin */ public RunnableGBall(double r) { super(r); } public void setEnclosureSize(double width, double height) { enclosureWidth = width; enclosureHeight = height; } public void setVelocity(double vx, double vy) { dx = vx; dy = vy; } @Override public void run() { // TODO Auto-generated method stub while (true) { advanceOneTimeStep(); pause(PAUSE_TIME); } } private void advanceOneTimeStep() { double bx = getX(); double by = getY(); double r = getWidth() / 2; if (bx < r || bx > enclosureWidth - r) dx = -dx; if (by < r || by > enclosureHeight - r) dy = -dy; move(dx, dy); } /* Private constants */ private static final int PAUSE_TIME = 20; /* Private instance variables */ private double enclosureWidth; private double enclosureHeight; private double dx; private double dy; }