2013-07-18 92 views
0

下面的代碼是不是whole.If你們需要整個代碼只是讓我know.My問題是,那麼當我勞克程序,我可以用箭頭看到紅色橢圓運動的背後它。當999米產生的矩形我謹一個ellpise,幀重新繪製和矩形再次和不同產生coords.I'd想實現在不改變所產生的rectangles.I知道這unwished效果理由位置移動的橢圓形,但不能修復it.Thank你!的Java重繪問題

public void paintComponent(Graphics g){ 
    random=new Random(); 
    super.paintComponent(g);  

     for(int i=0;i<=1000;i++){ 
     rX=random.nextInt(400); 
     rY=random.nextInt(400); 
     g.drawRect(rX,rY,20,20);    
     } 


    g.setColor(Color.red); 
    g.fillRect(x,y,20,20); 

} 

public void keyPressed(KeyEvent e) { 
    if(e.getKeyCode()==KeyEvent.VK_RIGHT){ 
     x=x+10; 
     repaint(); 
     if(x>480) 
      x=-10; 
    } 

回答

1

爲您的矩形的自定義類,用於保存他們的位置並生成構造函數中的隨機位置。喜歡的東西:

public class Rect { 

    private int x; 
    private int y; 
    private int width; 
    private int height; 

    public Rect() { 
     random=new Random(); 
     x=random.nextInt(400); 
     y=random.nextInt(400); 
     width=20; 
     height=20; 
    } 
    //getters and setters 
} 


private Rect rectangles[1000] = new Rect[](); 


public void paintComponent(Graphics g){ 
    super.paintComponent(g); 

    for (int i=0; i<1000;i++) { 
     g.drawRect(rectangles[i].getX(), rectangles[i].getY(), 
        rectangles[i].getwidth(), rectangles[i].getHeight()); 
    } 
} 
0

介紹一個布爾值,以保持跟蹤此組件是否已經繪製矩形之前或不private boolean hasBeenPainted;

然後在你的paintComponent:

public void paintComponent(Graphics g){ 
super.paintComponent(g); 
if(hasBeenPainted){return;}  
random=new Random(); 

for(int i=0;i<=1000;i++){ 
rX=random.nextInt(400); 
rY=random.nextInt(400); 
g.drawRect(rX,rY,20,20);    
} 


g.setColor(Color.red); 
g.fillRect(x,y,20,20); 
hasBeenPainted = true; 
} 
+0

'如果(hasBeenPainted!)'會比一回有 – nachokk

+0

恐怕漂亮有什麼東西不對的......當我移動橢圓形,從框架一切自敗。 –