Generate 100 random rectangles and ovals
Hello, Im a newbie :))
I'm working with a fairly simple task which I will create a program that draws a number of rectangles and ovals. The size and position of the rectangles and ovals are to be generated randomly.
But I have a problem, my code just draws ONE rectangle or oval, and I think it has something to do with the overlapping. So I need help finding my mistake.
RandomShape
Code:
import java.awt.*;
import javax.swing.*;
import java.lang.*;
public class RandomShape extends JFrame {
private int n; //Instansvariabel
public RandomShape() {}
public RandomShape(int antal) {
n = antal;
for(int i=1; i<n; i++)
add(generateRandomShape());
setBackground(Color.white);
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public Component generateRandomShape() {
double r1 = (int)(2*Math.random());
if (r1 == 0)
return new RandomRect();
else if (r1 == 1)
return new RandomOval();
else
return null;
}
public static void main (String[] arg) {
RandomShape r = new RandomShape(100);
}
}
RandomRect
Code:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class RandomRect extends JPanel {
private int width, height;
public RandomRect() {
width = randomPixel();
height = randomPixel();
setPreferredSize(new Dimension(width, height));
setOpaque(false);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(randomPixel(),randomPixel(), width, height);
}
private int randomPixel() {
int pix = (int)(Math.random()*400);
return pix;
}
}
RandomOval
Code:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class RandomOval extends JPanel {
private int width, height;
public RandomOval() {
width = randomPixel();
height = randomPixel();
setPreferredSize(new Dimension(width, height));
setOpaque(false);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillOval(randomPixel(),randomPixel(), width, height);
}
private int randomPixel() {
int pix = (int)(Math.random()*400);
return pix;
}
}
I appreciate all kind of help :)
Re: Generate 100 random rectangles and ovals
There are a couple of conceptual errors here. For one you must realize that a JFrame's contentPane uses BorderLayout by default, and so any comopnent added to the JFrame will cover over any that were added before.
But I think more importantly that your RandomRect and RandomOval classes should not extend JPanel but instead should create possibly a Rectangle2D and an Ellipse2D, both of which extend Shape, and your main GUI should hold a JPanel whose paintComponent has been overridden and an ArrayList of Shape or ArrayList<Shape>. Then create your random shapes and place them in the arraylist and in the one JPanel's paintComponent method iterate through the ArrayList drawing each shape.