You need to change your createPoints(...)
function to look like this:
private void createPoints(Point clickedPoint, int clickedColor) {
pointsToVisit.add(clickedPoint);
while(!pointsToVisit.isEmpty()) {
Point testPoint = pointsToVisit.poll();
if(testPoint.x >= 0 && testPoint.x < image.getWidth() && testPoint.y >= 0 && testPoint.y < image.getHeight()
&& image.getRGB(testPoint.x, testPoint.y) == clickedColor) {
while(testPoint.x > 0 && image.getRGB(testPoint.x-1, testPoint.y) == clickedColor) {
testPoint.x--;
}
currentLine = new Line(getColor(), 5);
currentLine.addPoint(new Point(testPoint));
pointsToVisit.add(new Point(testPoint.x, testPoint.y+1));
pointsToVisit.add(new Point(testPoint.x, testPoint.y-1));
image.setRGB(testPoint.x, testPoint.y, getColor().getRGB());
while(testPoint.x < image.getWidth()-1 && image.getRGB(testPoint.x+1, testPoint.y) == clickedColor) {
pointsToVisit.add(new Point(testPoint.x, testPoint.y+1));
pointsToVisit.add(new Point(testPoint.x, testPoint.y-1));
image.setRGB(testPoint.x, testPoint.y, getColor().getRGB());
testPoint.x++;
}
currentLine.addPoint(new Point(testPoint));
currentFill.addLine(currentLine);
}
}
}
(I sprinkled a couple of =
-signs into your if
condition to allow you to click into the top left corner of the image also, and a couple of +1
s and -1
s into you while
conditions to fix the bug described next)
Basically, what happens is after your first while loop you are either at the left edge of the image, in which case everything works fine, or your testPoint
is pointing at the first pixel that is NOT equal to clickedColor any more, in which case your second while loop terminates immediately.
BTW: Your code will probably lock up if you click on a point that is already set to your fill color (i.e. if clickedColor == getColor()
).