I am creating 100 particles at random location all over my JPanel using random function to calculate x and y. But I have two rectangles also drawn on the panel and I do not want my points to overlap on that area.
Is there any way, by which I can create the particles all over the JPanel except those areas covered by rectangle?
int x,y=0;
super.paintComponent(g);
for(int i=0;i<list.size();i++)
{
x=randomInteger(11,670); // bounds of x between which the particles should be generated (reduced by 1 each)
y=randomInteger(11,440); // bounds of y between which the particles should be generated (reduced by 1 each)
int radius = 4;
g.fillOval(x, y, radius, radius);
}
x=randomInteger(11,670);
y=randomInteger(11,440);
drawRobot(g,x,y,50);
createObstacles(g,150,225,100,40);
createObstacles(g,500,300,40,100);
int xpoints[] = {50, 40, 60, 120};
int ypoints[] = {50, 75, 100, 130};
int npoints = 4;
createPolygonObstacle(g,xpoints,ypoints,npoints);
}
private void createPolygonObstacle(Graphics g, int xpoints[], int ypoints[], int npoints)
{
g.fillPolygon(xpoints, ypoints, npoints);
}
private void createObstacles(Graphics g, int x, int y, int width, int height)
{
g.setColor(Color.BLACK);
g.fillRect(x, y, width, height);
}
private void drawRobot(Graphics g, int x, int y, int radius)
{
g.setColor(Color.GREEN);
g.fillOval(x, y, radius, radius);
}
private static int randomInteger(int min, int max)
{
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
You could take advantage of the Shape
API...
Rectangle rect = new Rectangle (x, y, width, height);
Then you could use it's contains
method to determine if it contains a given point...
if (rect.contains(x, y)) {
// You bad little particle...
}
You should also know that the Graphics2D
can also draw and paint Shape
, so you could also do...
((Graphics2D)g).fill(rect);
Which should make your life some what easier. As of Java 1.4 (I think), the paint engine is guaranteed to use Graphics2D
, so your paintComponent
method will always receive an instance of a Graphics2D
object.
Take a look at 2D Graphics for more details
Random r = new Random();
public void generateParticle(){
int x = r.nextInt();
int y = r.nextInt();
if(x > LeftEdgeOfRectangle || x < RightEdgeOfRectangle){
generateParticle();
return();
}
if(y > TopEdgeOfRectangle || y < BottomEdgeOfRectangle){
generateParticle();
return();
}
[drawParticleHere]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.