I'm writing a small drawing application. I'm trying to make a 'bucket fill' tool using a non-recursive implementation of the flood-fill algorithm.
However, if the user uses this tool a few times in a row with too short time intervals, it causes an OutOfMemoryError
in Java.
I would like to know how I can optimize my implementation so this error won't occur.
public void floodFill(int x, int y, Color targetColor, Color replacementColor) {
LinkedList<Point> stack = new LinkedList<Point>();
stack.add(new Point(x,y)); // adding the point where the mouse was clicked.
Point temp;
while( !stack.isEmpty() ){
temp = stack.pop();
int pixelColorRGB = drawingArea.getRGB( (int)temp.getX(), (int)temp.getY() );
Color pixelColor = new Color(pixelColorRGB, true);
if(pixelColor.equals(targetColor)){
g.setColor(replacementColor);
g.fillRect((int)temp.getX(), (int)temp.getY(), 1, 1);
if(this.contains((int) temp.getX() - 1, (int) temp.getY()))
stack.add( new Point( (int) temp.getX() - 1, (int) temp.getY() ) );
if(this.contains((int) temp.getX() + 1, (int) temp.getY()))
stack.add( new Point( (int) temp.getX() + 1, (int) temp.getY() ) );
if(this.contains((int) temp.getX(), (int) temp.getY() - 1))
stack.add( new Point( (int) temp.getX(), (int) temp.getY() - 1 ) );
if(this.contains((int) temp.getX(), (int) temp.getY() + 1))
stack.add( new Point( (int) temp.getX(), (int) temp.getY() + 1 ) );
}
}
}
Thank you