PDA

Click to See Complete Forum and Search --> : Using a Jpanel to draw random rectangles


Planet_x
Apr 7th, 2008, 11:01 PM
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()
{
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
}
}

ComputerJy
Apr 8th, 2008, 09:17 PM
And your question is??????

Planet_x
Apr 9th, 2008, 12:38 AM
Sorry here is updated code. I have in my package the MyRectangle class, a blank JForm class called RectGUI and the class for the panel RectGUIPanel. The following code is from my panel and it should create random rectangles okay but how do I display them inside of a Panel on my RectGUI form? Thanks alot for the assistance.


//Declare variables
private int x;
private int y;
private int width;
private int height;
private Color color;
Random rand = new Random();


public class RectanglePanel extends JPanel
{

public void displayRectangles()
{
// Declare an arraylist of MyRectangles
ArrayList<MyRectangle> myArray = new ArrayList<MyRectangle>();
int maxNumber = 300;

// Declare Frame and Panel
JFrame frame = new JFrame();
Container pane = frame.getContentPane();
RectanglePanel rect = new RectanglePanel();

// Set Frame attributes
frame.setSize(700, 500);
frame.setLocation(100,100);
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(" Rectangle Program");
frame.setVisible(true);

for (int i = 0; i < maxNumber; i++)
{
MyRectangle rec = createRandomRec();
myArray.add(rec);
rect.repaint();
}

}

public MyRectangle createRandomRec()
{
x = rand.nextInt();
y = rand.nextInt();
width = rand.nextInt();
height = rand.nextInt();
color = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
return new MyRectangle(x, y , width, height, color);


}
}

}