我已经实现了这个算法,它使用鼠标点击创建一个形状,然后你可以使用边界填充算法用一种颜色填充形状......只有部分形状被填充,然后我得到这个错误: 线程“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(未知来源)
知道有什么问题吗?这是我使用的边界填充算法....
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参数是鼠标点击和填充发生的坐标....
最佳答案
答案很简单,你导致堆栈溢出。该算法正在对大图像进行大量递归调用。您可以尝试类似的算法,但使用点堆栈而不是调用递归方法。带点堆栈的示例:
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));
}
}
}
关于java - 使用边界填充算法填充形状时出现堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23031087/