【问题标题】:JAVA2D - The objects that are moved are both in first and moved positionJAVA2D - 移动的对象都在第一个和移动的位置
【发布时间】:2013-12-16 01:56:46
【问题描述】:

我的程序有问题。我正在尝试将火车移动到铁轨上,这些火车用椭圆表示。当我尝试移动这些对象时,它们被绘制在新位置,但它们也被绘制在之前的位置。

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

// Trem 类

公共类 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;
}

}

可能是什么问题?

【问题讨论】:

  • 您提供的详细信息不足以找到问题
  • 我改变了位置,然后我尝试再次绘制它......
  • 如需尽快获得更好的帮助,请发帖SSCCE
  • @Ashish 您可以通过告诉他们需要哪些额外细节来帮助新手。 :-(
  • 顺便说一句 - this.getGraphics(); 这向我表明代码正在以错误的方式运行 custom painting

标签: java java-2d


【解决方案1】:

它们被绘制在新位置,但它们也被绘制在之前的位置。

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

【讨论】:

  • 如何在还车前清理该区域?
  • @user2928858,Andrew 为您提供了如何进行自定义绘画的链接。如果您按照示例代码执行 super.paintComponent(),则会自动为您清除背景。
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多