Issue
Okay, so a similar kind of question was asked here about finding color from a rectangle using this code (in an if statement, we would get a boolean):
Rectangle.getfill.equals(Color.BLACK).
Now, in my project I have filled my rectangles with images. Is there a way to find what image I put in my rectangle as similar to the code above finding what color was put on it.
if (((Rectangle) object).getFill().equals("C:\\Users\\shree\\IdeaProjects\\DOLP2\\src\\sample\\00.jpg"))
{
System.out.println("Image detected");
}
else
{
System.out.println("Not working");
}
Do you guys have any suggestions?
Solution
You need an Image pattern like you added to the image the reason yours isnt working is its comparing a filePath String to the fill of a rectangle which will never be equal but if you turn that filePath into an ImagePattern you've got yourself some Image detection. Check out my example.
public class Main extends Application {
//This is the Important part
private ImagePattern imagePattern = new ImagePattern(new Image(getClass().getResourceAsStream("FilePath.png")));
@Override
public void start(Stage stage) {
Rectangle rectangle = new Rectangle();
rectangle.setX(150.0f);
rectangle.setY(75.0f);
rectangle.setWidth(300.0f);
rectangle.setHeight(150.0f);
//Setting rectangle with the Image Pattern
rectangle.setFill(imagePattern);
Button button = new Button("Check");
button.setOnAction(event -> {
if(rectangle.getFill().equals(imagePattern))
System.out.println("We've got it Captain!!");
else
System.out.println("new fone who dis");
});
VBox vBox = new VBox(rectangle);
vBox.getChildren().add(button);
stage.setScene(new Scene(vBox));
stage.show();
}
public static void main(String[] args) { launch(args); }
}
You bet every time you click that button it prints out:
We've got it Captain!!
Answered By - Matt
Answer Checked By - Gilberto Lyons (JavaFixing Admin)