Search code examples
java-memidplcdui

Clearing the canvas with J2ME


I'm trying to create a program that shows two images at random locations and changes them every second. My problem however is when the image is redrawn I can still see the image in the previous position.

I'm using WTK 2.52 if that's relevant.

public void run()
{

    while(true)
    {
        dVert = rand.nextInt(136);
        dHorz = rand.nextInt(120);
        rVert = 136 + rand.nextInt(136);
        rHorz = 120 + rand.nextInt(120);

        try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            System.out.println("Error");
        }
        repaint();
    }
}

public void paint(Graphics g)
{
    int width = this.getWidth() / 2;
    int height = this.getHeight() / 2;
    g.drawImage(imgR, rVert, rHorz, g.TOP | g.LEFT);
    g.drawImage(imgD,dVert,dHorz,g.TOP | g.LEFT);

    //g.drawString(disp, width, 50, Graphics.TOP | Graphics.HCENTER);
    //g.drawString(centerMsg,width, height, Graphics.TOP | Graphics.HCENTER);
    System.out.println(width);
    System.out.println(height);
}

Complete code


Solution

  • You clear the canvas like this:

    g.setColor(0x000000); // Whatever color you wish to clear with
    g.setClip(0,0,getWidth(),getHeight());
    g.fillRect(0,0,getWidth(),getHeight());
    

    So just insert those lines before drawing the images.