2016-10-11 55 views
-2

随机三角形我有一个窗口打印500个三角形的一个问题。打印输出500个在Java

的代码,我创建的节目之一黄金三角,它只是改变,而我调整窗口,我必须让所有500个traingles出现一次。任何想法如何做到这一点?

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); 
    } 
} 
+2

当画布被绘制,你生成9个随机数字。这就是为什么它只在画布重新涂漆时才会改变。 9号,重复使用500次,不给你500个随机三角形。它可能会给你一个随机三角形500次。 – khelwood

+0

你画他们在彼此的顶部。 – eldo

回答

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); 
    } 
} 
+0

谢谢你,忘了这一点 – Biafra