如何使面板中的圆圈不接触边框?(Java图形)



我想在带有 Java 图形类的面板中创建具有随机直径、位置和颜色的圆。它工作正常,但是我有一个问题,圆圈经常接触或重叠边框。

如何使圆圈完全留在面板内?

提前感谢!

这是我用于创建圆圈的代码:

amount = rnd.nextInt(10);
    for (int i = 0; i < amount; i++){
        x = (50 + rnd.nextInt(panel.getWidth() - 50 + 1)) - 50;
        y = (50 + rnd.nextInt(panel.getHeight() - 50 + 1)) - 50;
        diameter = (rnd.nextInt(100));
        gr.setColor(new Color(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
        gr.fillOval(x, y, diameter, diameter);
        gr.drawString("" + (panel.getHeight() - y), x, y);
    }
    x = (50 + rnd.nextInt(panel.getWidth() - 50 + 1)) - 50;
    y = (50 + rnd.nextInt(panel.getHeight() - 50 + 1)) - 50;
    diameter = (rnd.nextInt(100));

如果您不知道圆的直径是多少,如何计算 x/y 位置?

首先,您需要计算直径。然后,您需要使用直径来确保x/y加上直径小于面板的宽度。

我不明白加 50 然后减去 50 的意义。我认为随机数应该是宽度减去直径。

最新更新