import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;

class RotatingLine extends JPanel implements ActionListener {
    private final int W;
    private final int H;
    
    private final Color[] colors = new Color [] { Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE};

    private final double length = 300;
    private final Point pivot;
    private final double delta = Math.toRadians(1.0);
    private double angle = 0.0;
    private Line2D line;

    private final Timer timer;

    public RotatingLine(int width, int height) {
        W = width;
        H = height;
        setPreferredSize(new Dimension(W, H));
        setBackground(Color.WHITE);
        pivot = new Point(W/2, H/2);
        line = new Line2D.Double(
            pivot.x,
            pivot.y,
            pivot.x + length * Math.cos(angle),
            pivot.y + length * Math.sin(angle)
        );
        timer = new Timer(10, this);
        timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        angle += delta;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D gr = (Graphics2D) g;
        gr.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        double x = pivot.x + length * Math.cos(angle);
        double y = pivot.y + length * Math.sin(angle);

        double deg = Math.toDegrees(angle);
        deg = (deg % 360);
        int sectorCount = colors.length;
        double sectorSize = 360.0 / sectorCount;
        int sector = (int)(deg / sectorSize) % sectorCount;
        Color color = colors[sector];

        gr.setStroke(new BasicStroke(4f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        gr.setColor(color);
        line.setLine(pivot.x, pivot.y, x, y);
        gr.draw(line);

        int r = 6;
        gr.setColor(color.darker().darker());
        gr.fillOval(pivot.x - r, pivot.y - r, r * 2, r * 2);
        gr.fillOval((int)x - r, (int)y - r, r * 2, r * 2);

        gr.setFont(gr.getFont().deriveFont(28f));
        gr.setColor(Color.BLACK);
        gr.drawString("Angle: " + String.format("%.1f°", deg), 20, 40);
    }
}

public class Main {
    public static void main(String[] args) {
        JFrame fr = new JFrame("Lab9-Var4");
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        int W = 800;
        int H = 800;
        RotatingLine panel = new RotatingLine(W, H);
        fr.setVisible(true);
        fr.getContentPane().add(panel);
        fr.setLocationRelativeTo(null);
        fr.pack();
    }
}
