使用边界填充算法填充形状时出现堆栈溢出错误

use*_*135 2 java stack-overflow algorithm graphics swing

我已经实现了这个算法,使用鼠标点击创建一个形状,然后你可以使用边界填充算法填充形状....只有部分形状填充,然后我得到这个错误: 在此输入图像描述 线程"AWT-EventQueue-0"中的异常java.lang.StackOverflowError java.util.HashMap.getEntry(未知来源)java.util.HashMap.get(未知来源)at sun.awt.AppContext.get(未知来源)来自位于javax.swing.RepaintManager的一个javax.swing.RepaintManager.getDelegate(未知来源)的com.sun.java.swing.SwingUtilities3.getDelegateRepaintManager(未知来源)位于javax.swing.JComponent.repaint的javax.swing.RepaintManager.addDirtyRegion(未知来源)来自java.awt.Component.repaint的未知来源(未知来源)

有什么想法错了吗?这是我使用的边界填充算法....

    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;
    }
Run Code Online (Sandbox Code Playgroud)

请注意,x和y参数是单击鼠标并进行填充的坐标....

ent*_*ios 5

答案很简单,你导致堆栈溢出.这个算法正在为大图像做很多递归调用.您可以尝试类似的算法,但使用点堆栈而不是调用递归方法.带点堆栈的示例:

    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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)