【问题标题】:Stack overflow error when filling a shape with boundary fill algorithm使用边界填充算法填充形状时出现堆栈溢出错误
【发布时间】:2014-04-12 13:36:05
【问题描述】:

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

知道有什么问题吗?这是我使用的边界填充算法......

    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参数是鼠标点击和填充发生的坐标....

【问题讨论】:

  • 为什么不改用Graphics2D#fill(Shape s)
  • 我只能使用这个算法:(
  • 请编辑您的问题以包含一个mcve,以展示您所描述的问题。在你的代码中,通过URL访问发布的图片,如图here;使用合成图像,如图here;或者使用UIManager图标,如图here
  • 我已经包含了图片....
  • 该方法被一个点调用,这导致该方法被其邻居调用,这导致该方法被其邻居调用,等等。鉴于要更新的​​点数很大,以及为每个点执行的大量操作(repaint()),我并不惊讶你达到了堆栈的限制。不要使用递归。使用迭代。

标签: java swing algorithm graphics stack-overflow


【解决方案1】:

答案很简单,您正在导致堆栈溢出。该算法正在对大图像进行大量递归调用。您可以尝试类似的算法,但使用点堆栈而不是调用递归方法。带点堆栈的示例:

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

【讨论】:

  • 刚刚投了赞成票!我不知道它是否是这个地方,但我需要知道......使用堆栈主要是将导致堆栈溢出的递归函数/方法转换为非递归函数/方法的最佳解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多