1

I am a Java beginner, and I am trying to make a program in which white balls appear on the screen constantly. There should be a few seconds pause between one ball appearing before the next, and the balls need to appear at different places on the screen. I need help using the RandomGenerator to make the balls appear at different places. Any help would be greatly appreciated!

private RandomGenerator rgen = new RandomGenerator();

//~ Constructor ...........................................................

// ----------------------------------------------------------
/**
 * Creates a new BubbleGame object.
 */
public void init()
{
    //call method to create regions
    CreateRegions();

    //add mouse listeners
    addMouseListeners();

    //loop to add bubbles
    while (true)
    {
        //create a filled bubble
        GOval bubble = new GOval (100, 100, 50, 50);
        bubble.setFilled(true);
        bubble.setColor(Color.WHITE);

        //randomly generate coordinates within the field
        int rgen = 

        //add the bubble and pause 
        add(bubble);
        Thread.sleep(3000);

    }
}
4

3 回答 3

0

您可以使用Random.nextInt(maxInt)生成一个介于 0 和 maxInt-1 之间的数字。

Random rnd = new Random();
rnd.nextInt(10); // 0-9
于 2013-11-15T07:47:58.057 回答
0

我猜你正在使用 Swing(或类似的技术)。在事件调度线程中使用 while(true) 总是一个坏主意。请改用 Swing Worker。

随机非常容易使用。Random.nextInt(n)会给你一个介于 0 和 n-1 之间的整数。

您还可以随机化气泡颜色、位置和大小。这是你的选择。您可以通过单击鼠标使它们消失。

于 2013-11-15T07:48:31.973 回答
0

这个函数将用你传递的_size、值和_minVal和_maxVal之间的随机数填充一个数组。所以如果你需要 4 个坐标传递 4 作为大小等。

public int[] makeRanArray(int _Size, int _minVal, int _maxVal)
{
    int[] arr = new int[_Size];

    for (int i = 0; i < _Size; i++){ 
        arr[i] = _minVal + (int)(Math.random() * _maxVal);
    }
    return arr;
}
于 2013-11-15T07:57:51.910 回答