I am programming a simple drawing application using Java. I am trying to use a recursive implementation of the Flood Fill algorithm as a bucket fill tool.
However, this always gives me StackOverFlowError. (No matter how small the area in which I use the bucket fill tool).
EDIT: Changed the code to make it more efficient. Another mistake.
Here is the code:
public void floodFill(int x, int y, Color targetColor, Color replacementColor) throws AWTException{
pixelColor = robot.getPixelColor(x,y);
g.setColor(replacementColor);
g.fillRect(x, y, 1, 1);
if(robot.getPixelColor(x-1, y).equals(targetColor))
floodFill(x-1, y, targetColor, replacementColor);
if(robot.getPixelColor(x+1, y).equals(targetColor))
floodFill(x+1, y, targetColor, replacementColor);
if(robot.getPixelColor(x, y-1).equals(targetColor))
floodFill(x, y-1, targetColor, replacementColor);
if(robot.getPixelColor(x, y+1).equals(targetColor))
floodFill(x, y+1, targetColor, replacementColor);
}
I would like to know if there is a way to use recursion with this algorithm and not get this error.
If not , what non-recursive implementations of this algorithm exist that I can use in my program?