gpt4 book ai didi

java - 为什么在使用 Flood Fill 算法时会出现 java.lang.StackOverflowError?

转载 作者:行者123 更新时间:2023-11-29 07:09:14 25 4
gpt4 key购买 nike

我的程序应该使用我在 boundaryFill4 方法中指定的颜色(开始时为黑色和白色)填充一个非常规形状。这是 myImage.png 的链接:https://dl.dropbox.com/u/41007907/myImage.png我使用了一个非常简单的洪水填充算法,但不知何故它不起作用......这是完整代码:

  import java.awt.Color;
import java.awt.Container;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MyPolygon extends JFrame {

private JLabel my;

public MyPolygon() throws InterruptedException {
createMy();
}

private void createMy() throws InterruptedException {
Container contentPane = getContentPane();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
contentPane.setSize(1000, 700);

my = new JLabel();
my.setIcon(new ImageIcon("myImage.png"));
my.setBounds(50, 50, 300, 300);
contentPane.add(my);

setSize(1000, 700);
setVisible(true);
setLocationRelativeTo(null);

int fill = 100;
boundaryFill4(100, 100, fill, 50);
}

// Flood Fill method
public void boundaryFill4(int x, int y, int fill, int boundary) {
int current;
current = getPixel(x, y);
if ((current >= boundary) && (current != fill)) {
setPixel(x, y, fill);
boundaryFill4(x + 1, y, fill, boundary);
boundaryFill4(x - 1, y, fill, boundary);
boundaryFill4(x, y + 1, fill, boundary);
boundaryFill4(x, y - 1, fill, boundary);
}
}

// Getting the color integer at specified point(x, y)
private int getPixel(int x, int y) {
Image img = ((ImageIcon) my.getIcon()).getImage();
BufferedImage buffered = new BufferedImage(img.getWidth(null),
img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
buffered.getGraphics().drawImage(img, 0, 0, null);
Color c = new Color(buffered.getRGB(x, y));
int current = buffered.getRGB(x, y);
return current;
}

// Setting the color integer to a specified point(x, y)
private void setPixel(int x, int y, int fill) {
Image img = ((ImageIcon) my.getIcon()).getImage();
BufferedImage buffered = new BufferedImage(img.getWidth(null),
img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
buffered.getGraphics().drawImage(img, 0, 0, null);
int red = fill;
int green = fill;
int blue = fill;
Color c = new Color(buffered.getRGB(x, y));
c = new Color(red, green, blue);
buffered.setRGB(x, y, c.getRGB());
}

// Main method
public static void main(String args[]) throws InterruptedException {
MyPolygon my = new MyPolygon();
my.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

为什么我会收到 StackOverflow 错误?我该如何更正它以使我的代码正常工作?

最佳答案

您可以尝试将递归方法(boundaryFill4 调用自身)转换为非递归方法。这样 JVM 堆栈就不会溢出。

另一种选择是增加堆栈的大小——参见 What is the maximum depth of the java call stack?

关于java - 为什么在使用 Flood Fill 算法时会出现 java.lang.StackOverflowError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15896898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com