To create a square in Java, you can use the Rectangle
class from the java.awt
package, which represents a rectangle with integer coordinates and dimensions.
Here's an example of how you can create a square in Java:
import java.awt.Rectangle; // ... int size = 100; Rectangle square = new Rectangle(0, 0, size, size);
In this example, the square
object is a Rectangle
instance with a size of 100 pixels. The Rectangle
class has four constructor arguments: the x and y coordinates of the top-left corner, and the width and height of the rectangle. By setting the width and height to the same value, you create a square.
You can use the setLocation()
and setSize()
methods of the Rectangle
class to change the position and size of the square.