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

时间:2014-04-12 13:36:05

标签: java swing algorithm graphics stack-overflow

我已经实现了这个使用鼠标点击创建形状的算法,然后你可以使用边界填充算法用颜色填充形状....只有部分形状被填充然后我得到这个错误: enter image description here     线程中的异常" AWT-EventQueue-0" java.lang.StackOverflowError的         在java.util.HashMap.getEntry(未知来源)         在java.util.HashMap.get(未知来源)         在sun.awt.AppContext.get(未知来源)         at com.sun.java.swing.SwingUtilities3.getDelegateRepaintManager(Unknown Source)         在javax.swing.RepaintManager.getDelegate(未知来源)         在javax.swing.RepaintManager.addDirtyRegion(未知来源)         在javax.swing.JComponent.repaint(未知来源)         在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;
    }

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

1 个答案:

答案 0 :(得分: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));
        }
    }
}