Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Class SquaresPanel is a JComponent that maintains a listof squares, can dis

ID: 3613029 • Letter: J

Question


Java Class SquaresPanel is a JComponent that maintains a listof squares, can display them, and is able to generate a new squareand add it its list of squares. Here is the plan: in fieldswe have SIDE (the length of the sides of each square), n (thenumber of squares we have), and x and y (arrays that store thepixel coordinates of their corners in indexes 0..n-1). Write amethod of SquaresPanel called addSquare that generates a randomsquare and adds it to its list of squares. The generated squareshould be entirely contained within our area and equally likely tobe anywhere. (Use getWidth() and getHeight() to determine theareas of this SquaresPanel.)
Java Class SquaresPanel is a JComponent that maintains a listof squares, can display them, and is able to generate a new squareand add it its list of squares. Here is the plan: in fieldswe have SIDE (the length of the sides of each square), n (thenumber of squares we have), and x and y (arrays that store thepixel coordinates of their corners in indexes 0..n-1). Write amethod of SquaresPanel called addSquare that generates a randomsquare and adds it to its list of squares. The generated squareshould be entirely contained within our area and equally likely tobe anywhere. (Use getWidth() and getHeight() to determine theareas of this SquaresPanel.)

Explanation / Answer

All code is in the method public void addSquare()

The square must have a side length less than width and height,and greater than 0. Therefore:

intmax=(int)Math.max(getWidth(), getHeight());
int side=(int)(Math.random()*(max))+1;

Now we must find the x and y pixel coordinates, keeping inmind that the side length determines where it could be:

intx=(int)(Math.random()*(getWidth()-side));
int y=(int)(Math.random()*(getHeight()-side));

Now you have the x and y coordinates, and the side length ofthe square. Now you have the x and y coordinates, and the side length ofthe square.
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote