在Java中在屏幕上添加计数器

时间:2014-03-22 18:23:36

标签: java

我刚刚在大学开始学习Java课程,我的最后一个任务是使用GOval创建一个简单的球并使其从窗口边框反弹。我想在球上添加一个简单的计数器,每次反弹都会增加。

我知道如何制作计数点击次数,我只是不知道如何让它在屏幕上显示,把它放在我的球上然后跟着它。

public class Ball extends GraphicsProgram{
    private static final double BALL_SIZE=50;
    private static final double SPEED=3;
    private static final double GRAVITY=0;
    private static final double ELASTICITY=1;
    private static final double PAUSE = 1000/48.0;
    private static boolean HIT = false;
    private static boolean MOVE_TOP = false;
    private static int COUNTER=0;

    public void run(){
        GOval ball = makeBall();
        add(ball);
        bounce(ball);
    }

    private GOval makeBall(){
        GOval result = new GOval (0,0,BALL_SIZE,BALL_SIZE);
    result.setFilled(true);
    result.setColor(Color.BLACK);
    return result;

}

private void bounce(GOval ball){
    double dx=SPEED;
    double dy=20;
    while(true){
        ball.move(dx,dy);
        if(MOVE_TOP==false){
            dy+=GRAVITY;
            }
        else{
            dy-=GRAVITY;
            }
        if(ballHitBottom(ball) && dy>=0){
            dy*=-ELASTICITY;
            COUNTER++;
            if(HIT==false)
            HIT=true;

        }
        if(ballHitTop(ball) && dy<=0){
            if(HIT){
            dy*=-ELASTICITY;
            COUNTER++;
            }
        }

        if(ballHitRight(ball) && dx>=0){
            if(HIT){
            dx*=-ELASTICITY;
            COUNTER++;
            }
        }

        if(ballHitLeft(ball) && dx<=0){
            if(HIT){
            dx*=-ELASTICITY;
            COUNTER++;
            }
        }
        pause(PAUSE);
    }
}
private boolean ballHitBottom(GOval ball){
    MOVE_TOP=true;
    double bottomY=ball.getY() + ball.getHeight();
    return bottomY >= getHeight();
}

private boolean ballHitTop(GOval ball){
    double topY=ball.getY();
    MOVE_TOP=false;
    return topY <= 0;
}

private boolean ballHitRight(GOval ball){
    double rightX=ball.getX() + ball.getWidth();
    return rightX >= getWidth();
}

private boolean ballHitLeft(GOval ball){
    double leftX=ball.getX();
    return leftX <= 0;
}
}

2 个答案:

答案 0 :(得分:2)

private GLabel label;

public void run(){
    GOval ball = makeBall();
    label = new GLabel(String.valueOf(COUNTER), BALL_SIZE/2, BALL_SIZE/2);
    add(ball);
    add(label);
    bounce(ball);
}

moveball.move(dx,dy)下:

label.move(dx,dy);

move内,pause(PAUSE)以上:

label.setLabel(String.valueOf(COUNTER));

答案 1 :(得分:-1)

要让计数器更新,请在每次击球时使用label.revalidate()