我有一个弹跳球类扩展了GraphicsProgram。我希望能够将它嵌入我的博客。根据{{3}}帖子,我可以使用Java Web start来达到目的。但我是编程新手,我的程序非常小。所以我想坚持使用Java Applet。但是要使用Java Applet,我需要将类扩展为JApplet。正如我所提到的,我的弹跳类扩展了GraphicsProgram。所以我无法将其用作Java applet。 究竟需要确保在浏览器中实现任何类并作为Java Applet运行?
/**
* This program graphically simulates a bouncing ball.
*/
package Lecture_Examples;
import acm.graphics.GOval;
import acm.program.GraphicsProgram;
public class BouncingBall extends GraphicsProgram{
private static final long serialVersionUID = -1154542047805606083L;
/**
* Diameter of the ball
*/
private static final int DIAM_BALL = 30;
/**
* Amount of velocity to be increased as a result of gravity
*/
private static final int GRAVITY = 3;
/**
* Animation delay or pause between the ball moves
*/
private static final int DELAY = 50;
/**
* Initial x and y pos of the ball
*/
private static final int X_START = DIAM_BALL /2;
private static final int Y_START = DIAM_BALL /2;
/**
* X velocity
*/
private static final double X_VEL = 5;
/**
* Amount of Y velocity reduction when the ball bounces
*/
private static final double BOUNCE_REDUCE = 0.9;
/**
* starting x and y velocities
*/
private double xVel = X_VEL;
private double yVel = 0.0; //starting from rest
/*
* ivar
*/
private GOval ball;
public void run(){
setUp(); //set's up initial pos of the ball
//simulation ends when the ball goes off right hand of the screen
while(ball.getX() < getWidth()){
moveBall();
checkForCollision();
pause(DELAY);
}
}
/**
* Checks if the ball touches the floor of the canvas and then update velocity and position of the ball
*/
private void checkForCollision() {
//determine if the ball has dropped below the floor
if(ball.getY() > (getHeight() - DIAM_BALL)){
//Change the ball's y velocity to bounce it up the floor with bounce_reduce effect
yVel = -yVel *BOUNCE_REDUCE;
//assuming that the ball will move an amount above the floor
//equal to the amount it would have dropped below the floor. This will
//sure that the ball doesn't bulge to the floor while bouncing.
double diff = ball.getY() - (getHeight() - DIAM_BALL);
ball.move(0, -2*diff);
}
}
/**
* Moves the ball
*/
private void moveBall() {
yVel += GRAVITY; //Add gravity to produce moment to or away from the floor
ball.move(xVel, yVel);
}
/**
*Creates and place the ball
*/
private void setUp() {
ball = new GOval(X_START, Y_START, DIAM_BALL, DIAM_BALL); //Creates teh ball
ball.setFilled(true); //fill black
add(ball); //add to canvas
}
}