How to check an Imagepattern of a Rectangle in Javafx?

Asked

Viewed 41 times

1

I’m trying to check in this method if my Square, which inherits from Rectangle, was filled with an Imagepattern through the getFill function():

 public boolean HouseIsValid(House Square) {

    return (Square.getFill().equals(green) || Square.getFill().equals(lightgreen));
}

Being green and lightgreen two Imagepatterns which are declared in this method in my constructor:

 public void setImagePatterns() {

    ImageView image = new ImageView("/Images/greenhouse.jpg");
    green = new ImagePattern(image.getImage());

    image = new ImageView("/Images/lightgreenhouse.jpg");
    lightgreen = new ImagePattern(image.getImage());
}

There is in the class of my Square a method to determine his Imagepattern, here is that at some point of my main code, I change the Imagepattern to those above:

public void setFill(String url) {

    ImageView image = new ImageView(url);
    setBackground(new ImagePattern(image.getImage()));

    setFill(background);
}

However, it returns false when it should return true. I would like to know what is wrong in the validation of the first method. Thanks in advance.

1 answer

0


The method is returning false because the objects compared are different. In java, when you create a class, it inherits from the class Object. One of the methods of Object is the equals. The method equals of Object returns true if the two instances compared are the same.

In your case, you create an instance at that point:

green = new ImagePattern(image.getImage());

But at this other point, you create another instance:

setBackground(new ImagePattern(image.getImage()));

So when do you compare the ImagePattern, you are comparing different objects.

So that the method equals work differently, for example, return true if the paths are the same, it is necessary to override it. In this case, the validation cannot be done using the equals. Unfortunately the classes ImagePattern and Paint do not provide any method to perform this test. You could save the path of the images and do the validation through the path.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.