在java中打印出500个随机三角形

时间:2016-10-11 11:55:52

标签: java canvas

我在窗口中打印500个三角形时遇到问题。

我创建的代码显示了一个traingle,它只在我调整窗口大小时才会改变,我必须立即显示所有500个traingle。知道怎么做吗?

import javax.swing.*;
import java.awt.*;
import java.util.Random;


public class BoringTriangle extends Canvas {

    public void paint(Graphics g){

        Random nmb = new Random();

        //Colours

        int x1 = nmb.nextInt(200) + 1;
        int x2 = nmb.nextInt(200) + 1;
        int x3 = nmb.nextInt(200) + 1;



        int x4 = nmb.nextInt(500) + 1;
        int x5 = nmb.nextInt(500) + 1;
        int x6 = nmb.nextInt(500) + 1;



        int x7 = nmb.nextInt(500) + 1;
        int x8 = nmb.nextInt(500) + 1;
        int x9 = nmb.nextInt(500) + 1;




        for(int z = 1; z<=500; z++) {
            g.setColor(new Color(x1, x2, x3));
            g.fillPolygon(new int[]{x4, x5, x6}, new int[]{x7, x8, x9}, 3);

        }
    }

    public static void main( String[] args )
    {
        // You can change the title or size here if you want.
        JFrame win = new JFrame("Boring Traingle lul");
        win.setSize(800,600);
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        BoringTriangle canvas = new BoringTriangle();
        win.add( canvas );
        win.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:2)

将随机数的生成移动到循环体。否则,您将绘制相同的三角形500次:

for(int z = 0; z < 500; z++) {
    int x1 = nmb.nextInt(200) + 1;
    int x2 = nmb.nextInt(200) + 1;
    int x3 = nmb.nextInt(200) + 1;

    int x4 = nmb.nextInt(500) + 1;
    int x5 = nmb.nextInt(500) + 1;
    int x6 = nmb.nextInt(500) + 1;

    int x7 = nmb.nextInt(500) + 1;
    int x8 = nmb.nextInt(500) + 1;
    int x9 = nmb.nextInt(500) + 1;

    g.setColor(new Color(x1, x2, x3));
    g.fillPolygon(new int[]{x4, x5, x6}, new int[]{x7, x8, x9}, 3);
}

如果您还希望在重新绘制时保持三角形相同,请将值保存到合适的数据结构中:

private Color[] colors;
private int[][][] coordinates;
BoringTriangle() {
    Random nmb = new Random();
    colors = new Color[500];
    coordinates = new int[500][2][];
    for (int i = 0; i < 500; i++) {
        colors[i] = new Color(nmb.nextInt(200) + 1, nmb.nextInt(200) + 1, nmb.nextInt(200) + 1);
        coordinates[i][0] = new int[] {nmb.nextInt(500) + 1, nmb.nextInt(500) + 1, nmb.nextInt(500) + 1};
        coordinates[i][1] = new int[] {nmb.nextInt(500) + 1, nmb.nextInt(500) + 1, nmb.nextInt(500) + 1};
    }
}

public void paint(Graphics g) {
    for(int i = 0; i < colors.length; i++) {
        g.setColor(colors[i]);
        g.fillPolygon(coordinates[i][0], coordinates[i][1], 3);
    }
}