使用命令java设置Color和Radius

时间:2016-01-30 10:14:39

标签: java

我希望能够让用户更改球的颜色和半径,我还希望能够在创建球时更改球的颜色。

我尝试使用setColor,但我没有让它发挥作用。

这是我的代码:

import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

public class Ball {

    public static final double BILLION = 1_000_000_000.0;

    private double x, y; // position of the balls center
    private double dx, dy; // velocity measured in pixels/second
    private double radius;
    private Color color;

    public Ball(double x0, double y0) {
        x = x0;
        y = y0;
        radius = 10;
        color = Color.YELLOW;
    }

    public double getX() {
        return x;
    }


    public double getY() {
        return y;
    }

    public void setX(double newX) {
        x = newX;
    }

    public void setY(double newY) {
        y = newY;
    }

    public double getRadius() {
        return radius;
    }

    public double getDx() {
        return dx;
    }

    public double getDy() {
        return dy;
    }

    public void setVelocity(double newDx, double newDy) {
        dx = newDx;
        dy = newDy;
    }

    public void moveTo(double newX, double newY) {
        x = newX;
        y = newY;
    }

    public void setColor(Color col) {
        color = col;   
    }

    public void move(long elapsedTimeNs) {
        x += dx * elapsedTimeNs / BILLION;
        y += dy * elapsedTimeNs / BILLION;
    }

    public void paint(GraphicsContext gc) {
        gc.setFill(color);
        // arguments to fillOval: see the javadoc for GraphicsContext
        gc.fillOval(x - radius, y - radius, radius * 2, radius * 2);
    }

    public boolean intersectsArea(
            double rectX, double rectY,
            double rectWidth, double rectHeight) {


        double closestX = clamp(x, rectX, rectX + rectWidth);
        double closestY = clamp(y, rectY, rectY + rectHeight);

        double distanceX = x - closestX;
        double distanceY = y - closestY;

        return (distanceX * distanceX) + (distanceY * distanceY)
                < (radius * radius);
    }

    private double clamp(double value, double lower, double upper) {
        if (value < lower) {
            return lower;
        }
        if (value > upper) {
            return upper;
        }
        return value;
    }
}

有关如何进行的任何提示? 谢谢!

1 个答案:

答案 0 :(得分:0)

我的猜测是你在设置颜色后不调用paint,你需要重绘以改变颜色