如何确保在随机位置的JFrame上绘制的点与已绘制的形状不重叠?

时间:2014-07-24 01:54:40

标签: java swing

我使用随机函数在我的JPanel上的随机位置创建100个粒子来计算x和y。但我在面板上也绘制了两个矩形,我不希望我的点在该区域上重叠。

有什么方法可以在JPanel上创建粒子,除了那些矩形覆盖的区域?

            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;
        }

2 个答案:

答案 0 :(得分:1)

您可以利用Shape API ...

Rectangle rect = new Rectangle (x, y, width, height);

然后您可以使用它的contains方法来确定它是否包含给定点...

if (rect.contains(x, y)) {
    // You bad little particle...
}

您还应该知道Graphics2D也可以绘制和绘制Shape,所以您也可以... {/ p>

((Graphics2D)g).fill(rect);

哪个应该让你的生活变得更轻松。从Java 1.4开始(我认为),绘制引擎保证使用Graphics2D,因此您的paintComponent方法将始终接收Graphics2D对象的实例。

请查看2D Graphics了解详情

答案 1 :(得分:0)

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]
}