Java,为什么我的图形要画出它们应该在的帧/范围之外?
因此,我正在制作一个程序,目前在大小为1024x768的JFrame上随机绘制随机大小(6-9之间)的填充圆。我遇到的问题是,即使在我编写了一个规则,确保所有的圆都在1024x768 JFrame内,这些圆也会超出所需的边界。以下是应为每个圆生成正确位置的代码段:Java,为什么我的图形要画出它们应该在的帧/范围之外?,java,swing,graphics,jframe,Java,Swing,Graphics,Jframe,因此,我正在制作一个程序,目前在大小为1024x768的JFrame上随机绘制随机大小(6-9之间)的填充圆。我遇到的问题是,即使在我编写了一个规则,确保所有的圆都在1024x768 JFrame内,这些圆也会超出所需的边界。以下是应为每个圆生成正确位置的代码段: private static KillZoneLocation generateLocation(){ int genX,genY; int xmax = 1024 - generatedGraphic.getRadi
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;
}
GenerateGraphic是包含上述方法的类中的全局变量,返回一个介于6和9之间(含6和9)的数字
generatedGraphic.getRadius()从该算法返回一个随机数int radius=7+(int)(Math.random()*9);之前已通过不同的方法生成该编号。这个方法只是一个getter。并非每次调用此方法时都会生成半径编号
IsOverlapping(位置)只是检查以确保圆不会与已放置在JFrame上的另一个圆重叠
位置。设置。。。这些只是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());
}
}
}
当您从generatedGraphic.getRadius()开始时;并且只能转到xmax/ymax
然后使用@JasonNichols的答案,从(左,上)(0,0)开始填充椭圆形到宽度-直径。正确的代码应为
genX = (int)(Math.random()*xmax);
genY = (int)(Math.random()*ymax);
请记住,将在左上角使用genX/genY,椭圆将按getRadius()的值延伸。你要减去半径的大小,然后再加上两次!在genX/Y作业中,以及在绘制椭圆形时,都会有一次。要更快获得更好的帮助,请发布一个。我们肯定也需要查看绘制方法。切勿直接在JFrame中绘制。在JPanel或JComponent扩展类的
paintComponent(…)
方法中绘制,并在该方法中获取此绘图面板的尺寸,以便对大小没有疑问。是的,这也是我应该做的事情。我不知道它是从左上角画的。是的,圆角半径为0,2*radius;我也忽略了它+1给杰森。
genX = (int)(Math.random()*xmax);
genY = (int)(Math.random()*ymax);