Creamsoda Johnson
Creamsoda Johnson

Reputation: 1

How can I change the color of a rectangle?

Where am i going wrong with my logic to simply change the color of the rectangle when clicked?

        square.setFill(null);
        square.setStroke(Color.BLACK);
        setAlignment(Pos.CENTER);
        getChildren().addAll(square);

        setOnMouseClicked(event ->{
            if(event.getButton() == MouseButton.PRIMARY) {              
                square.setFill(Color.BLUE);
            }
            else if(square.getFill().equals(Color.BLUE)) {
                    square.setFill(Color.BLACK);
            }


        });

Upvotes: 0

Views: 320

Answers (3)

ScottFoster1000
ScottFoster1000

Reputation: 617

The problem you might find with using a variable is that you have to have a variable which you track for each object that you want to support changing color on or your objects that change color will all be triggered on the same variable.

I think you can keep your original code, I think the issue is your if statement:

setOnMouseClicked(event ->{
    if(event.getButton() == MouseButton.PRIMARY) {              
        square.setFill(Color.BLUE);
    }
    else if(square.getFill().equals(Color.BLUE)) {
            square.setFill(Color.BLACK);
    }

If you look at it, the condition is if the getButton is the Primary and if true, it will always set it to blue and if the user didn't use the primary button, it will only set to black if the color is blue.

You want something like:

setOnMouseClicked(event ->{
    if(event.getButton() == MouseButton.PRIMARY) {              
       if(!square.getFill().equals(Color.BLUE)) {
           square.setFill(Color.BLUE);
       }
       else
               square.setFill(Color.BLACK);
       }
   }
}

Upvotes: 0

Sai Dandem
Sai Dandem

Reputation: 9869

I think you dont require a boolean flag. What you are doing can be done as below:

setOnMouseClicked(event -> {
    if (event.getButton() == MouseButton.PRIMARY) {
       square.setFill(square.getFill() == Color.BLUE ? Color.BLACK : Color.BLUE);
    }
});

Upvotes: 1

Creamsoda Johnson
Creamsoda Johnson

Reputation: 1

I ended up using a boolean to flag if the rectangle is blue or not.

        square.setFill(null);
        square.setStroke(Color.BLACK);
        setAlignment(Pos.CENTER);
        getChildren().addAll(square);

        setOnMouseClicked(event ->{
            if(event.getButton() == MouseButton.PRIMARY) {              
                if(!isBlue) {
                    square.setFill(Color.BLUE);
                    isBlue = true;
                }
                else if(isBlue) {

                    square.setFill(Color.BLACK);
                    isBlue = false;
                }
            }
        });

Upvotes: 0

Related Questions