gpt4 book ai didi

Java,为什么我的图形超出了它们应该在的框架/范围?

转载 作者:行者123 更新时间:2023-11-30 11:34:40 24 4
gpt4 key购买 nike

因此,我正在制作一个程序,该程序当前在大小为 1024x768 的 JFrame 上随机绘制随机大小(包括 6-9 之间)的实心圆。我遇到的问题是,即使在我编写了一条规则以确保所有圆都落在 1024x768 JFrame 内之后,这些圆仍然落在了所需的边界之外。下面是应该为每个圆圈生成正确位置的代码段:

private static KillZoneLocation generateLocation(){
int genX,genY;
int xmax = 1024 - generatedGraphic.getRadius();
int ymax = 768 - generatedGraphic.getRadius();
KillZoneLocation location = new KillZoneLocation();
do{
genX = generatedGraphic.getRadius() + (int)(Math.random()*xmax);
genY = generatedGraphic.getRadius() +(int)(Math.random()*ymax);
location.setXcoord(genX);
location.setYcoord(genY);
generatedLocation = location;
}while(isOverlaping(location));

return location;
}

generatedGraphic 是来自包含上述方法的类的全局变量,返回 6 到 9 之间的数字(含 6 和 9)

generatedGraphic.getRadius() 从该算法返回一个随机数 int radius = 7 + (int)(Math.random()*9);该号码之前已通过不同的方法生成。这个方法只是一个 setter/getter 。并不是每次调用该方法都会生成半径数。

isOverlaping(locations) 只是检查以确保该圆不与已放置在 JFrame 上的另一个圆重叠。

location.set... 这些只是 setter 方法。

我认为这只是一个愚蠢的逻辑错误,但我似乎仍然无法弄清楚为什么圆圈打印在框架之外。

我故意避免再发布代码,因为它会让您感到困惑,因为该程序的范围比我描述的要大得多,并且有十几个文件相互交织。我调试了这段代码并实现了返回的数字: genX = generatedGraphic.getRadius() + (int)(Math.random()*xmax); genY = generatedGraphic.getRadius() +(int)(Math.random()*ymax);

返回超出范围的数字。

绘画类:

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;

public class KillZoneGUI extends JFrame{

public KillZoneGUI(){
setSize(1024,768);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);

}

public static void main(String s[]) {
GenerateKillZone.setup(1024,768);
new KillZoneGUI();
}

public void paint(Graphics g){
for(Robot r: KillZone.getRobots()){
g.setColor(r.getGraphic().getColor());
g.fillOval(
r.getLocation().getXcoord(),
r.getLocation().getYcoord(),
r.getGraphic().getRadius(),
r.getGraphic().getRadius());
}

}
}

最佳答案

正确的代码应该是

genX = (int)(Math.random()*xmax);
genY = (int)(Math.random()*ymax);

记住 Graphics2D.fillOval()将使用 genX/genY 作为左上角,椭圆将扩展 getRadius() 的值。您正在减去半径的大小,但随后将其加回两次!一次在您的 genX/Y 作业中,一次在您绘制椭圆形时。

关于Java,为什么我的图形超出了它们应该在的框架/范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15524942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com