user2928858
user2928858

Reputation: 39

JAVA2D - The objects that are moved are both in first and moved position

I have a problem with my program. I'm trying to move trains over a rail, these trains are represented by ellipses. When I try to move these objects, they are drawn in the new position, but they are also drawn in the previous position.

trensPretos is a linkedlist of trem class:

'public LinkedList trensPretos = new LinkedList();'

Here is my code:

public void AtualizaTrensPretos()
        {
            int currentX;
            int currentY;

            // trens pretos se movem
            for (Trem t:trensPretos)
            {
                while(t.get_x() < 1100)
                {
                    currentX = t.get_x();
                    currentY = t.get_y();

                    t.setNew_x(currentX + moveX);

                    // antes da linha reta
                    if (t.get_x() < 270)
                    {
                        t.setNew_y(currentY + moveY);
                    }
                    else if(t.get_x() > 730)
                    {// depois da linha reta
                        t.setNew_y(currentY - (moveY+1));
                    }

                    setChanged();
                    notifyObservers(t);
                }

                // removo o trem após ele passar pelo cruzamento
                //          trensPretos.remove(t);
            }
        }
// Observer

// recebo trem e desenho
g2d = (Graphics2D) this.getGraphics();
        if (arg instanceof Trem)
        {
            if (g2d != null)
            {               
                g2d.setColor(((Trem) arg).getColor());
                g2d.fill(((Trem) arg).getEllipse());
            }
        }

// Trem class

public class Trem {

private int posX;
private int posY;

private Color corTrem;
private Ellipse2D formaDoTrem;
private int sizeX = 30;
private int sizeY = 30;

public Trem(Color corDoTrem)
{
    formaDoTrem = new Ellipse2D.Double();
    this.corTrem = corDoTrem;
}

public Color getColor()
{
    return this.corTrem;
}

public void setNew_x(int x)
{
    this.posX = x;
}

public void setNew_y(int y)
{
    this.posY = y;
}

public int get_x()
{
    return this.posX;
}

public int get_y()
{
    return this.posY;
}

public Ellipse2D getEllipse()
{
    this.formaDoTrem.setFrame(posX, posY, sizeX, sizeY);
    return this.formaDoTrem;
}

}

What could be the problem?

Upvotes: 2

Views: 49

Answers (1)

camickr
camickr

Reputation: 324108

they are drawn in the new position, but they are also drawn in the previous position.

You need to clear the background area first before repainting the trains.

Upvotes: 1

Related Questions