So, I am making a program that currently draws filled circles of a random size (between 6-9 inclusive) randomly on a JFrame of size 1024x768. The problem I am having, is that even after I coded in a rule that should ensure that all the circles fall within the 1024x768 JFrame, the circles fall outside of the desired boundaries. Below is the code segment that should generate the correct location for each circle:
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 is a global variable from the class containing the method above and returns a number between 6 and 9 inclusive
generatedGraphic.getRadius() returns a random number from this algorithm int radius = 7 + (int)(Math.random()*9); The number has been generated prior by a different method. This method is just a getter. The radius number is not generated every time this method is called.
isOverlaping(locations) just checks to make sure the circle does not overlap another circle that is already placed on the JFrame.
location.set... Those are just setter methods.
I'm thinking this is just a silly logic error, but I still can't seem to figure out why the circles are printing outside of the frame.
I am purposely avoiding posting anymore code because it will confuse you since the program has a much larger scope then I have described and there are a dozen files all interwinded. I debugged this code and realized numbers being returned by: genX = generatedGraphic.getRadius() + (int)(Math.random()*xmax); genY = generatedGraphic.getRadius() +(int)(Math.random()*ymax);
Return numbers out of range.
Draw class:
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());
}
}
}