View Full Version : Need help randomly putting rectangles into a JPanel

04-08-2008, 06:22 AM
Just need some assistance with drawing random rectangles inside of a JPanel when the form loads. I have a seperate rectangle class created that has a constructor for the following :

public Rectangle(int newX, int newY, int newWidth,
int newHeight, Color newColor)
x = newX;
y = newY;
width = newWidth;
height = newHeight;
color = newColor;

It also has a paint method. I also have another JFrame class for my GUI created but I am new to GUIs and not sure how to do this. My panel is named panelRectangles and when the form loads it is supposed to create a whole bunch of random rectangles in the panel to be used for sorting. I am supposed to use the following code to make a seperate class that extends JPanel and will be used to draw my rectangles but not sure where it goes.. in my GUI Frame Class? Thanks for any assistance.

staticclass RectanglePanel extends JPanel
public RectanglePanel()
setOpaque(false); // don't paint all the bits
protectedvoid paintComponent(Graphics g)
// code to paint the rectangles goes here

04-08-2008, 10:34 PM
You should implement:

public void paint(Graphics g);

as part of RectanglePanel. Then use the rendering context to draw whatever it is you need, in this case being the variable g.

You can then do one of two things. The first thing would be to have the Rectangle objects have their own draw(Graphics g); method, or the second is to make a call from the Graphics object passed through the paint() method defined in RectanglePanel.

The first method would require you keeping a reference to all Rectangle objects and iterating through a list of them calling each of their draw(Graphics g) methods, and the second option means using the Graphics object and explicitly making calls.

So in RectanglePanel you would have the following perhaps:

public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D)g; // personally I prefer using Graphics2D because of the extended functionality

g2D.drawRectangle( /* params in here */ );

alternatively you could do the following

public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D)g;

for(Rectangle r : rectangleList) {

So as you can see in that example, you'd store a list of all the objects and iterate through them drawing each one to screen by passing a reference to the Graphics2D object.

Pretty straight forward really.