0

我有一个扩展 GraphicsProgram 的弹跳球类。我希望能够将它嵌入到我的博客中。根据这篇文章,我可以为此目的使用 Java Web start。但我是编程新手,我的程序很小。所以我想坚持使用Java Applet。但要使用 Java Applet,我需要将类扩展为 JApplet。正如我所提到的,我的 bouncingball 类扩展了 GraphicsProgram。所以我不能将它用作 Java 小程序。确保任何类都可以作为 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
    }
}
4

0 回答 0