I want to fill a polygon using 8-connected boundary fill. The code for 4-connected boundary fill works. However, when I add the four additional statements to test diagonal positions for 8-connected boundary fill, I get ArrayIndexOutOfBoundsException: Coordinate out of bounds! error. What is the problem and how to solve it?
private void bfill(int x, int y, Color fillColour, Color borderColour){
Stack<Point> points = new Stack<>();
points.add(new Point(x, y));
while(!points.isEmpty()) {
Point currentPoint = points.pop();
x = currentPoint.x;
y = currentPoint.y;
Color interiorColour = new Color(bi.getRGB(x, y));
if (!interiorColour.equals(borderColour) && !interiorColour.equals(fillColour)){
setPixel(x, y); //draw pixel
points.push(new Point(x+1, y));
points.push(new Point(x-1, y));
points.push(new Point(x, y+1));
points.push(new Point(x, y-1));
//Error occurs when the next four lines are uncommented for 8-connected boundary fill
/*points.push(new Point(x+1, y+1));
points.push(new Point(x+1, y-1));
points.push(new Point(x-1, y-1));
points.push(new Point(x-1, y+1));*/
}
}
}
Edit: Following gpasch's answer, I included bounds checking. However, the program runs endlessly. What is wrong with the bounds checking?
if (!interiorColour.equals(borderColour) && !interiorColour.equals(fillColour)){
if (x > -1 && y > -1 && x < getWidth() && y < getHeight()){
setPixel(x, y); //draw pixel
if (x+1 < getWidth()) points.push(new Point(x+1, y));
if (x-1 > -1) points.push(new Point(x-1, y));
if (y+1 < getHeight()) points.push(new Point(x, y+1));
if (y-1 > -1) points.push(new Point(x, y-1));
if (x+1 < getWidth() && y+1 < getHeight()) points.push(new Point(x+1, y+1));
if (x+1 < getWidth() && y-1 > -1) points.push(new Point(x+1, y-1));
if (x-1 > -1 && y-1 > -1) points.push(new Point(x-1, y-1));
if (x-1 > -1 && y+1 > getHeight()) points.push(new Point(x-1, y+1));
}
}
}