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

/** A component that displays a flower with petals appearing after a delay. */
public class FlowerTimer extends JPanel {

  /** Program that displays a flower in a window. */
  public static void main(String[] args) {
    JFrame frame = new JFrame("Flower");
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    FlowerTimer flower = new FlowerTimer();
    flower.setBackground(Color.white);

    frame.add(flower);
    frame.setVisible(true);

    // Draw another petal every 500 ms.
    new Timer(500, e -> {
          flower.setPetalCount(flower.getPetalCount() + 1);
          flower.repaint();
        }).start();
  }

  private int petalCount = 0;

  /** returns the number of petals that will be drawn (up to 8). */
  public int getPetalCount() { return petalCount; }

  /** Sets the number of petals to display to the given number. */
  public void setPetalCount(int petalCount) { this.petalCount = petalCount; }

  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(g);  // paint background

    Graphics2D g2 = (Graphics2D) g;

    // Draw the stem.
    g2.setStroke(
        new BasicStroke(10, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    g2.setColor(new Color(0, 128, 0));  // green
    g2.drawLine(toScreenX(100), toScreenY(190), toScreenX(100), toScreenY(70));

    // Draw the center.
    g2.setColor(new Color(255, 165, 0));  // orange
    g2.fillOval(toScreenX(75), toScreenY(45), toScreenX(50), toScreenY(50));

    // Draw eight petals at N, NE, E, SE, S, SW, W, NW positions on the center.
    int petalWidth = toScreenX(20);
    int petalHeight = toScreenY(20);
    g2.setColor(new Color(255, 192, 203));  // pink

    if (petalCount > 0)
      g2.fillOval(toScreenX(90), toScreenY(35), petalWidth, petalHeight);
    if (petalCount > 1)
      g2.fillOval(toScreenX(108), toScreenY(42), petalWidth, petalHeight);
    if (petalCount > 2)
      g2.fillOval(toScreenX(115), toScreenY(60), petalWidth, petalHeight);
    if (petalCount > 3)
      g2.fillOval(toScreenX(108), toScreenY(78), petalWidth, petalHeight);
    if (petalCount > 4)
      g2.fillOval(toScreenX(90), toScreenY(85), petalWidth, petalHeight);
    if (petalCount > 5)
      g2.fillOval(toScreenX(72), toScreenY(78), petalWidth, petalHeight);
    if (petalCount > 6)
      g2.fillOval(toScreenX(64), toScreenY(60), petalWidth, petalHeight);
    if (petalCount > 7)
      g2.fillOval(toScreenX(72), toScreenY(42), petalWidth, petalHeight);
  }

  /** Converts an x-coordinate from a 200-width screen to the actual width. */
  private int toScreenX(int x) {
    return Math.round(x * getWidth() / 200f);
  }

  /** Converts an y-coordinate from a 200-width screen to the actual width. */
  private int toScreenY(int y) {
    return Math.round(y * getHeight() / 200f);
  }

}