How to check an ImagePattern of a Rectangle in JavaFX?

1

I'm trying to check in this method if my Square, which inherits from Rectangle, was filled with an ImagePattern via 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 a method in my Square class to determine the ImagePattern of it, so in a given moment 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 validating the first method. Thanks in advance.

    
asked by anonymous 17.12.2017 / 13:58

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 Object class. One of the Object methods is equals . The method equals of Object returns true if the two instances compared are the same.

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

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

At this point, however, you create another instance:

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

So when you compare ImagePattern , you're comparing different objects.

For the equals method to work differently, for example, return true if the paths are the same, you must overwrite it. In your case, validation can not be done using equals . Unfortunately, the ImagePattern and Paint classes do not provide any method to perform this test. You could save the path of the images and validate through the path.

    
20.12.2017 / 01:51