user1882022 user1882022 - 16 days ago 7
Java Question

Java Thread issue for refreshing the frame

I have written code for bouncing ball using java thread. But i unable to clear it / refresh it when ball moves down. Please hep me here.

import java.awt.*;

class myFrame
extends Frame
{
public void paint(Graphics g)
{
try
{
for(int i=10;i<=400;i++)
{
g.drawOval(100,i+100,50,50);update(g);
repaint();
Thread.sleep(500);

}
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}

class BallTest
{
public static void main(String cp[])
{
myFrame mf = new myFrame();
mf.setSize(500,500);
mf.setVisible(true);
}
}


Thanks

Answer

You shouldn't be calling update(). If your intent was to clear the previous ball, this works:

import java.awt.*;

class myFrame
extends Frame
{
    public void paint(Graphics g)
    {
        try
        {
            for(int i=10;i<=400;i++)
            {
                g.drawOval(100,i+100,50,50);
                repaint();
                Thread.sleep(500);
                Rectangle r = getBounds();
                g.clearRect(r.x, r.y, r.width, r.height);
            }
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}

class BallTest
{
    public static void main(String cp[])
    {
        myFrame mf = new myFrame();
        mf.setSize(500,500);
        mf.setVisible(true);
    }
}

However, you should probably setup a timer calling repaint instead of explicitly delaying the paint() method.

Comments