0

下面的代码不是完整的。如果你们需要完整的代码,请告诉我。我的问题是,当我启动程序时,我可以看到红色椭圆可以通过箭头移动,后面有 999 个生成的矩形。当我移动一个椭圆时,框架会重新绘制和矩形在不同的坐标上再次生成。我想在不改变生成矩形位置的情况下实现移动椭圆。我知道这种不希望的效果的原因,但无法修复。谢谢!

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

2 回答 2

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());
    }
}
于 2013-07-18T17:34:11.120 回答
0

引入一个布尔值来跟踪该组件之前是否绘制过矩形private boolean hasBeenPainted;

然后在你的油漆组件中:

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;
}
于 2013-07-18T15:54:58.650 回答