Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Question on generating random rectangles inside a JPanel

807601Apr 8 2008 — edited Apr 8 2008
I have a rectangle class that has a constructor which initializes a rectangle shape with an int x and y coordinate for screen position and ints for width/height. Also have a color variable for color of the rectangles. I have to create a GUI that will allow the user to push a button and have a whole bunch of random rectangles appear inside a JPanel on the form. After reading I understand I am supposed to create a seperate class for the panel and have it extend the JPanel and then put my draw method/ paint method to create random rectangles of the rectangle class here. I'm just not sure how to randomly fill up the Panel with rectangles.. and do I need to make a panel on the form (which is called GUIForm and is a JFrame Form but is empty) or do I let the class I create for a JPanel draw its own panel into the JFrame Form. Any help appreciated thanks.

Paint Method from my Rectangle class:
public void paint(Graphics g)
{
  g.setColor(color);
  g.fillRect(x, y, width, height);
  g.setColor(color.RED);
  g.drawRect(x, y, width, height);
}
Code I am having troubles with: wont let me use the BorderFactory method or create any rectangles, not sure what to put here.
public class RectGUIPanel extends javax.swing.JPanel {


    public RectGUIPanel() 
   {
  
     super();
     setOpaque(false); // don't paint all the bits
     setBorder(BorderFactory.createLineBorder(Color.black));
   }
   
    
    protectedvoid paintComponent(Graphics g) 
   {
// code to paint the rectangles goes here
   }

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 6 2008
Added on Apr 8 2008
8 comments
1,145 views