Question

Code below is not whole.If you guys need whole code just let me know.My problem is, then when I lauch program I can see red ellipse movable by arrows and 999 generated rectangles behind it.When I move an ellpise, frame repaints and rectangles are generated again and on different coords.I'd like to achieve moving ellipse without changing positions of generated rectangles.I know reason of this unwished effect, but can't fix it.Thank you!

    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;
    }
Was it helpful?

Solution

Create a custom class for your rectangles that holds their positions and generates the random locations in the constructor. Something like:

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

OTHER TIPS

Introduce a boolean to keep track of whether this component has drawn rectangles before or not private boolean hasBeenPainted;

Then in your 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top