简体   繁体   中英

Java: How can I nest my circles?

Having a tough time placing these circles inside each other. I need them evenly spaced and within each other. Do you see what I'm doing incorrectly?

  import javax.swing.*;
  import java.awt.*;

  public class JNestedCircles extends JFrame
  {
    public void paint(Graphics c)
    {
    super.paint(c);
    setTitle("JNestedCircles");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    final int TOTAL_CIRCLES = 15;
    final int GAP = 17;
    int arcSize, x = 40, y = 80;
    int x1 = 500;
    int y1 = 500;
    for(arcSize = 0; arcSize < TOTAL_CIRCLES; arcSize++)
    {
        c.drawOval(x, y, x1, y1);
        x += GAP;
        y += GAP;
        x1 -= GAP ;
        y1 -= GAP ;
    }       
    }   
    public static void main(String[] args)
    {
    JNestedCircles aFrame = new JNestedCircles();
    final int WIDTH = 585;
    final int HEIGHT = 640;
    aFrame.setSize(WIDTH, HEIGHT);
    aFrame.setVisible(true);
  aFrame.setLocationRelativeTo(null);
    }
  }

It looks like you have the right idea, you just need to do:

    x1 -= 2 * GAP ;
    y1 -= 2 * GAP ;

This is because the second two args are width and height, not ending position. You correctly offset your x, y by GAP with your increment, which specifies the top-left corner of your circle. Now you just need width/height to reduce by 2 * GAP each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM