我的程序應該使用邊界填充方法中指定的顏色(開頭爲黑色和白色)填充非規則形狀。這裏是鏈接到myImage.png:https://dl.dropbox.com/u/41007907/myImage.png 我用一個很簡單的洪水填充算法,但它不以某種方式工作...以下是完整的代碼:使用Flood Fill算法時,爲什麼會出現java.lang.StackOverflowError?
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'會導致無限循環。它沒有這麼難調試,並找到自己的答案... – BobTheBuilder 2013-04-09 08:31:48
可能重複[什麼是堆棧溢出錯誤?](http://stackoverflow.com/questions/214741/what-is-a-stack-溢出錯誤) – fglez 2013-04-10 09:25:45