Reputation: 2838
I want to fill an applet with blue color. I am doing this using paint(Graphics g) method. While filling the applet, i get StackOverFlowException after 8-10 seconds. I want to get rid of it. Please suggest me what to do or correct me if i am doing wrong. I asked someone about this, he said it store locations and removing them later, so that stack is always nearly empty. Please help me.
Code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
public class Flooding extends Applet
{
boolean[][] mark;
boolean justOnce = true;
@Override
public void init()
{
mark = new boolean[800][600];
this.setSize(100, 500);
this.setPreferredSize(new Dimension(100, 500));
this.setVisible(true);
}
@Override
public void start()
{
setBackground(Color.WHITE);
setForeground(Color.BLACK);
}
@Override
public void paint(Graphics g)
{
if(justOnce)
{
super.paint(g);
justOnce = false;
}
for (int row=0; row<500; row++)
{
for (int col=0; col<100; col++)
{
flood(mark, row, col, g);
}
}
}
private static void sleep(int msec)
{
try
{
Thread.currentThread().sleep(msec);
}
catch (InterruptedException e) { }
}
public void flood( boolean[][] mark, int row, int col, Graphics g)
{
if (row < 0) return;
if (col < 0) return;
if (row > 100) return;
if (col > 500) return;
if (mark[row][col]) return;
g.setColor(Color.BLUE);
g.drawLine(row, col, row, col);
mark[row][col] = true;
repaint();
sleep(1);
flood(mark, row - 1, col, g);
flood(mark, row, col, g);
flood(mark, row + 1, col, g);
flood(mark, row-1, col-1, g);
flood(mark, row, col-1, g);
flood(mark, row+1, col-1, g);
flood(mark, row-1, col + 1, g);
flood(mark, row, col + 1, g);
flood(mark, row+1, col + 1, g);
}
}
Upvotes: 0
Views: 67
Reputation: 14169
Look at your code: first call to flood()
is with coordinates (0, 0)
which later calls flood()
with coordinates (1, 0)
which calls flood()
... With your dimensions, you get to a recursion 500 levels deep. Change your code to not using recursion.
(You can of course increase the stack size with -Xss
, but your code is broken, so fix that instead.)
Upvotes: 1