2013-12-15 27 views
2

我的程序有問題。我試圖在火車上移動火車,這些火車以橢圓形表示。當我嘗試移動這些物體時,它們被繪製在新的位置,但它們也被繪製在之前的位置。JAVA2D - 移動的對象都處於第一個和移動的位置

trensPretos是TREM類的鏈表:

'公共鏈表trensPretos =新鏈表();'

這裏是我的代碼:

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

//珍珍類

公共類珍珍{

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

}

可能是什麼問題呢?

+0

您提供的詳細信息不足以找到問題 – Ashish

+0

我改變位置,然後嘗試再次繪製它... – user2928858

+0

爲了更好地提供幫助,請發佈[SSCCE](http://sscce.org /)。 –

回答

1

他們被繪製在新的位置,但他們也繪製在以前的位置。

您需要先清理背景區域,然後再重新打印列車。

+0

如何在清理列車前清除該區域? – user2928858

+1

@ user2928858,Andrew爲您提供了關於如何進行自定義繪製的鏈接。如果您按照示例代碼執行super.paintComponent(),則會爲您清除背景自動。 – camickr