创建随机形状

时间:2018-04-05 16:26:57

标签: java swing

  1. 我已声明我的变量以获取SecureRandom类的随机值。
  2. 在我的paintComponent方法中,我有一个for循环以防创建许多随机形状。
  3. 如果Random值等于零,则绘制一个矩形形状,否则绘制一个椭圆。
  4. 当我运行我的项目时,我只得到一个形状,因为我的所有变量都在我的循环之外。 任何提示请如何实现这种情况(创建许多随机形状)? 感谢。
  5. 我的声明:

    SecureRandom RC = new SecureRandom();
    
    int r = RC.nextInt();
    int g2 = RC.nextInt();
    int b = RC.nextInt();
    int cl = (r + g2 + b) / 3;
    int choice = RC.nextInt(2);
    int x = RC.nextInt(230);
    int y = RC.nextInt(250);
    int w = RC.nextInt(115);
    int h = RC.nextInt(125);
    

    我的paintComponent方法:

        for(int i = 1; i <= 10; i++)
        { 
            super.paintComponent(g);
            Color mc = new Color(cl);
    
            if(choice == 0)
            {
                g.setColor(mc);
                g.fillRect(x, y, w, h);
            }
    
            else
            {
                g.setColor(mc);
                g.fillOval(x, y, w, h);
            }
        }
    

2 个答案:

答案 0 :(得分:1)

  

当我运行我的项目时,我只得到一个形状,因为我的所有变量都在我的循环之外。

那是对的。你需要在循环中调用choice = RC.nextInt(2);,并根据你得到的值创建一个新的椭圆或矩形。

编写用于创建随机椭圆和矩形的单独函数可能是一个好主意(尽管不是绝对必要的)。这样你的循环就不会被这段代码弄得乱七八糟。

答案 1 :(得分:0)

您需要将用于创建随机形状的所有变量放入for循环中,以便在for循环的每次迭代后为每个变量创建一个新的随机值。只需获取所需的所有变量,并将它们放在只能在for循环中使用的for循环中。你希望整个变量都相同,你在for循环之前初始化。

以下代码在每次迭代时创建一个完全随机的矩形或椭圆

for(int i = 1; i <= 10; i++)
{ 
    int r = RC.nextInt();
    int g2 = RC.nextInt();
    int b = RC.nextInt();
    int cl = (r + g2 + b) / 3;

    int x = RC.nextInt(230);
    int y = RC.nextInt(250);
    int w = RC.nextInt(115);
    int h = RC.nextInt(125);

    super.paintComponent(g);
    Color mc = new Color(cl);

    int choice = RC.nextInt(2);
    if(choice == 0)
    {
        g.setColor(mc);
        g.fillRect(x, y, w, h);
    }
    else
    {
        g.setColor(mc);
        g.fillOval(x, y, w, h);
    }
}
相关问题