JAVA2D-移动的对象都位于第一个和移动的位置

JAVA2D-移动的对象都位于第一个和移动的位置,java,java-2d,Java,Java 2d,我的程序有问题。我试着让火车越过轨道,这些火车用椭圆表示。当我尝试移动这些对象时,它们会在新位置绘制,但它们也会在前一个位置绘制 trensPretos是trem类的链接列表: 'public LinkedList trensPretos=new LinkedList();' 这是我的密码: public void AtualizaTrensPretos() { int currentX; int currentY;

我的程序有问题。我试着让火车越过轨道,这些火车用椭圆表示。当我尝试移动这些对象时,它们会在新位置绘制,但它们也会在前一个位置绘制

trensPretos是trem类的链接列表:

'public LinkedList trensPretos=new LinkedList();'

这是我的密码:

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());
            }
        }
}

有什么问题吗

它们在新位置绘制,但也在以前的位置绘制


在重新粉刷火车之前,您需要先清除背景区域。

您提供的详细信息不足以找到问题。请更改位置,然后我尝试再次绘制……为了更快获得更好的帮助,请发布一条。@Ashish您可以通过告诉新手需要哪些额外的详细信息来帮助他们:-(顺便说一句,
this.getGraphics();
这向我表明代码走错了方向。在重新绘制火车之前,我如何清除该区域?@user2928858,Andrew为您提供了有关如何进行自定义绘制的链接。如果您按照示例代码执行一个超级.paintComponent(),则背景会自动为您清除。
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;
}