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 に答える