Open up the “CanvasPanel” file. Before we complete the “randomBallSpawnButton”, we need to add a little more code to the “CanvasPanel” class. Add the code as shown here to do this.
First off, we need to be able to get some random numbers, so we create a new “Random” class variable called “numberGenerator.”
Then we instantiate/construct it inside the “CanvasPanel” constructor.
Next, we need the ability for our canvas to return a random number within its bounds. Otherwise, we run the risk of spawning things outside of the canvas. Complete the code as shown to do so.
This was way back in one of our first projects, but remember that “nextInt” returns a random number between 0 and the number you give it. So, this will always give us an x between 0 and width, and a y between 0 and height.
Now with all of that done, go back to the “ControlPanel” file and add the code as shown here to complete the “randomBallSpawnButton”.
This code is very simliar to the other button’s code. The main difference here is that for the x and y, we use the new functions we just made to get a random x and a random y.
Once this has been completed, go ahead and test it out! You should now be able to create balls randomly around the game, if not, go back and check your code for any errors.