mercredi 29 novembre 2023

not changing colors in java GraphicsProgram

The problem is asking me to spawn a circle on the canvas with a click. This part works fine. The next part is if i click a circle it needs to keep switching to random colors from: green, yellow, black, red , blue until the color is green. The code I wrote kinda does change the color but the change doesn't appear visually.

`import java.awt.Color; import java.awt.event.MouseEvent;

import acm.graphics.*; import acm.program.GraphicsProgram; import acm.util.RandomGenerator;

public class VAR4N5 extends GraphicsProgram {

private RandomGenerator rgen = RandomGenerator.getInstance();

private final static int CIRCLE_D = 40;
private final static int DELAY = 50;

private GOval clickedCircle = null;

public void run() {
    addMouseListeners();
}

public void mouseClicked(MouseEvent e) {

    if (getElementAt(e.getX(), e.getY()) == null) {
        drawCircle(e.getX(), e.getY());
    } else {
        clickedCircle = (GOval) getElementAt(e.getX(), e.getY());
        changeColor();
    }
}



private void drawCircle(double xClick, double yClick) {
    double x = xClick - CIRCLE_D / 2.0;
    double y = yClick - CIRCLE_D / 2.0;
    GOval circle = new GOval(CIRCLE_D, CIRCLE_D);
    circle.setFilled(true);
    circle.setFillColor(rgen.nextColor());
    add(circle, x, y);
}

private void changeColor() {
    int randomNum = 0;
    while (true) {
        randomNum = rgen.nextInt(1, 5);
        if (randomNum == 1) {
            clickedCircle.setFillColor(Color.GREEN);
            break;
        }
        if (randomNum == 2) {
            clickedCircle.setFillColor(Color.BLACK);
        }
        if (randomNum == 3) {
            clickedCircle.setFillColor(Color.YELLOW);
        }
        if (randomNum == 4) {
            clickedCircle.setFillColor(Color.RED);
        }
        if (randomNum == 5) {
            clickedCircle.setFillColor(Color.BLUE);
        }
        clickedCircle.setLocation(clickedCircle.getX(), clickedCircle.getY());
        pause(DELAY);
    }
}

}




Aucun commentaire:

Enregistrer un commentaire