0

これは、私が望むように機能しない私のコードの一部です.ループ内の長方形がペイントされると、X軸とY軸に乱数を使用したにもかかわらず、毎回同じ場所にペイントされます.四角形を 5 回 (ループに設定されているため) 描画し、それぞれをランダムな座標に描画します。コード全体が必要な場合は、お知らせください。ありがとうございます!

    public void paintComponent(Graphics g){
    random=new Random();
    rX=random.nextInt(500);
    rY=random.nextInt(500);
    super.paintComponent(g);    

        for(int i=0;i<=5;i++){
        g.fillRect(rX,rY,20,20);
        }


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

}
4

1 に答える 1

3

現在、コードは座標を 1 回だけ生成します。(指摘してくれたJon Skeetに感謝)

5 つの異なる三角形を描画する場合は、呼び出しをrandom.nextIntループ内に移動する必要があります。

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

    super.paintComponent(g);    

    for(int i=0; i<=4; i++){
        rX=random.nextInt(500);
        rY=random.nextInt(500);
        g.fillRect(rX,rY,20,20);
    }


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

}
于 2013-07-18T08:00:17.240 に答える