If loops aren't a requirement, you could look into using a recursive approach. Something like this method would work. Every time a circle is drawn, you subtract 5 from the radius until the radius is less than 5.
private void displayOvals(Graphics g, int radius, int centerx, int centery) {
if (radius >= 5) {
g.drawOval(centerx - radius, centery - radius, 2 * radius, 2 * radius);
displayOvals(g, radius - 5, centerx, centery);
}
}
Here is an example
import javax.swing.*;
import java.awt.*;
public class RecursiveCirclesPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int radius = (int) (Math.min(getWidth(), getHeight()) * 0.9 / 2);
int centerx = getWidth() / 2;
int centery = getHeight() / 2;
displayOvals(g, radius, centerx, centery);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
private void displayOvals(Graphics g, int radius, int centerx, int centery) {
if (radius >= 5) {
g.drawOval(centerx - radius, centery - radius, 2 * radius, 2 * radius);
displayOvals(g, radius - 5, centerx, centery);
}
}
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, new RecursiveCirclesPanel());
}
}
EDIT
What you want to do is have a List
of BullsEye
objects in your BullsEyeComponent
class. Then just loop through them in the paintComponent
method. What I would do, instead of just taking x
and y
arguments to the BullEye
object, is instead to take the a radius
argument. You can use that raidus in your draw method, doing some calculations on it to get the x, y, width, and height
.
In your BullsEyeComponent
you can add the BullsEye
objects to the List<BullsEye>
. Use a while
loop, saying something like
while (radius >= 5 ) {
// add to the list a BullsEye (passing it the radius) and decrease the radius
}
This is pretty much the same as using the recursive method, but instead you make the recursion an iteration (loop)
NOTE: This is more of an OOP approach. You could do the same just using one BullsEye
object, and while looping, decrease the radius and draw another circle in the draw
method. So you have two options.
HINT #1
class BullsEye {
public void draw(Graphics2D g2, int radius, int xCenter, int yCenter) {
while (radius >= 5) {
g2.drawOval(xCenter - radius, yCenter - radius, 2 * radius, 2 * radius);
radius -= 15;
}
}
}
HINT #2
class BullsEyeComponent extends JComponent {
BullsEye bullsEye = new BullsEye();
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int radius = (int) (Math.min(getWidth(), getHeight()) * 0.9 / 2);
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
bullsEye.draw(g2, radius, xCenter, yCenter);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}