因此,我正在编写一个程序,它当前在大小为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);这个数字之前是由另一种方法生成的。这个方法只是一个getter。并不是每次调用此方法时都会生成半径数。
isOverlaping(位置)只是检查以确保该圆不会与已放置在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());
}
}
}发布于 2013-03-20 21:57:16
正确的代码应为
genX = (int)(Math.random()*xmax);
genY = (int)(Math.random()*ymax);请记住,Graphics2D.fillOval()将使用genX/genY作为左上角,椭圆将通过getRadius()的值进行扩展。你在减去半径的大小,然后把它加回来两次!一次是在genX/Y赋值中,另一次是在绘制椭圆时。
发布于 2013-03-20 21:53:18
int xmax = 1024 - 2 * generatedGraphic.getRadius();
int ymax = 768 - 2 * generatedGraphic.getRadius();因为您是从generatedGraphic.getRadius();开始的,所以只能转到xmax/ymax。
然后使用@JasonNichols的答案,宽度从( fillOval,top) (0,0)开始。
https://stackoverflow.com/questions/15524942
复制相似问题