user2228135 user2228135 - 5 months ago 55
Java Question

Stack overflow error when filling a shape with boundary fill algorithm

i have implemented this algorithm that creates a shape using mouse clicks and then u can fill the shape with a color using the boundary fill algorithm.... Only part of the shape is filled and then i get this error :
enter image description here
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.util.HashMap.getEntry(Unknown Source)
at java.util.HashMap.get(Unknown Source)
at sun.awt.AppContext.get(Unknown Source)
at com.sun.java.swing.SwingUtilities3.getDelegateRepaintManager(Unknown Source)
at javax.swing.RepaintManager.getDelegate(Unknown Source)
at javax.swing.RepaintManager.addDirtyRegion(Unknown Source)
at javax.swing.JComponent.repaint(Unknown Source)
at java.awt.Component.repaint(Unknown Source)

Any idea whats wrong? Here is the boundary fill algorithm im using....

public void BoundaryFill(int x, int y, Color bColor, Color fColor){
int current = bI.getRGB(x, y);
if((current != bColor.getRGB()) && (current != fColor.getRGB())){
//bI.setRGB(x, y, fColor.getRGB());
bI.setRGB(x, y, fColor.getRGB());

repaint();

BoundaryFill(x+1, y, bColor, fColor);

BoundaryFill(x-1, y, bColor, fColor);

BoundaryFill(x, y-1, bColor, fColor);

BoundaryFill(x, y+1, bColor, fColor);


}
else
return;
}


Note that the x and y parameters are the coordinates where the mouse is clicked and the filling takes place....

Answer

Answer is simple, you are causing stack overflow. This algorithm is doing lot of recursive calls for big image. You can try similar algorithm but using points stack instead of calling recursive methods. Sample with points stack:

    public void BoundaryFill(int initialX, int initialY, Color bColor, Color fColor){
    Stack<Point> points = new Stack<>();
    points.add(new Point(initialX, initialY));

    while(!points.isEmpty()) {
        Point currentPoint = points.pop();
        int x = currentPoint.x;
        int y = currentPoint.y;

        int current = bI.getRGB(x, y);
        if((current != bColor.getRGB()) && (current != fColor.getRGB())){
            //bI.setRGB(x, y, fColor.getRGB());
            bI.setRGB(x, y, fColor.getRGB());

            repaint();

            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));
        }
    }
}
Comments