Reputation: 145
I am trying to fill a circle, i made in my canvas with some dots, using the floodfill method. Only the circle should be filled, nothing outside. So i made a list, in which i stored all the points that are already marked in the canvas.
private LinkedList<Point> filledpoints = new LinkedList<Point>();
In the filling method i'd now like to overgive a starting point, and then i'd love to check if it is possible to draw a dot here, or if there is already a dot there. I googled the Flood Fill Algorithm of course, and came up with something like that - i tried to use the algorithm with either 8 neighbours:
// checking if a dot can be drawn:
if (!filledpoints.contains(new Point(startX, startY))) {
drawDot(g,startX,startY,Color.ORANGE);
filledpoints.add(new Point(startX,startY));
floodfill(g, startX + 1, startY);
floodfill(g, startX, startY + 1);
floodfill(g, startX - 1, startY);
floodfill(g, startX, startY - 1);
floodfill(g, startX + 1, startY + 1);
floodfill(g, startX - 1, startY + 1);
floodfill(g, startX - 1, startY - 1);
floodfill(g, startX + 1, startY - 1);
}
Or with only four neighbours:
if (!filledpoints.contains(new Point(startX, startY))) {
drawDot(g,startX,startY,Color.ORANGE);
filledpoints.add(new Point(startX,startY));
floodfill(g, startX + 1, startY);
floodfill(g, startX, startY + 1);
floodfill(g, startX - 1, startY);
floodfill(g, startX, startY - 1);
}
I also tried out something like storing the values from the points in the list into an array, and then checking with the array, but it didnt help. It always gives me this error in the first recursive call line:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at sun.java2d.SunGraphics2D.fillOval(Unknown Source)
What am i doing wrong at this point? Or in other words: am i even on the right track? I never got this error before, and i am really confused at this point. Is it even the right way i am trying to do that? Any hint would be helpful, it doesn't even need to be a code solution! :/
My paint method (which is called to execute the program) looks like this if needed:
public void paint(Graphics g) {
// drawing the circle:
for (Circle c : circles) {
drawCircle(g, c.radius, c.centerX, c.centerY);
}
if (!startpoints.isEmpty()) {
for (Point p : startpoints) {
floodfill(g, p.x, p.y);
}
}
}
Startpoints is the array in which i stored the first point inside the circle (if there is a more elegant way of doing this, please be kind and let me know). Please let me know if you need any other information concerning my code for this question. I'll edit it in a few seconds if needed!
Upvotes: 0
Views: 597
Reputation: 2460
You don't check for edges. filledpoints
will contain point like Point(-1, 0)
. Then the fillOval
can't draw that and throws an exception.
Upvotes: 3