Just drawing ovals won't help you, and instead you need to use an object that has more heft to it, more internal data and behaviors that will allow you to do these queries. Fortunately, such a type of object exists in the Graphcs2D libraries: the Shape interface and its subtypes, here Ellipse2D. Create an Ellipse2D object and then you can draw it using Graphics2D g2d.draw(myEllipse)
and check for intersection using the .intersects(...)
method.
e.g.,
// declare and initialize fields
private int x = 0;
private int y = 0;
private Ellipse2D myEllipse1 = new Ellipse2D.Double(x, y, 24, 24);
private Ellipse2D myEllipse2 = new Ellipse2D.Double(x, y, 100, 142);
// draw your shapes in the drawing JPanel
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// change the g2d's color?
g2d.draw(myEllipse1);
// change the g2d's color?
g2d.draw(myEllipse2);
// ...
}
elsewhere, such as in a Swing Timer's ActionListener:
// set location values to proper value
x = somethingNew;
y = somethingElseNew;
// create new Ellipse2D objects based on the x,y changes
myEllipse1 = new Ellipse2D.Double(x, y, 24, 24);
myEllipse2 = new Ellipse2D.Double(x, y, 100, 142);
// test for intersection
if (myEllipse1.intersects(myEllipse2) {
// do something
}
// ask the GUI to re-draw itself
repaint();