Hi guys I'm trying to learn animation/graphics(they're synonymus to me) what would really help me is a working model of a line turning on an intersection. I've searched around and all i can find is clocks and stuff but all i want is the basic code to cause a line to turn on a centre(like a single clock hand). I just want to learn motion from it, a working code would be massively appreciated. Thanks in advance.

Dani AI

Generated

Brief context: the original request was for a single line to "turn on a centre" like a clock hand. already showed two solid approaches (manual trig and an anchored end). An alternative that is simpler to reason about is to rotate the Graphics2D coordinate system about the pivot and draw the hand along the x‑axis. That removes most sign/axis confusion and keeps paint math minimal.

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

public class PivotRotatePanel extends JPanel {
    private double angle = 0;
    private final int length = 80;

    public PivotRotatePanel() {
        setPreferredSize(new Dimension(300, 300));
        new Timer(16, e -> { angle += Math.toRadians(1); repaint(); }).start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int cx = getWidth() / 2, cy = getHeight() / 2;
        g2.rotate(angle, cx, cy);            // rotate around pivot
        g2.setStroke(new BasicStroke(4f));
        g2.setColor(Color.BLUE);
        g2.drawLine(cx, cy, cx + length, cy); // draw to the right; rotation handles the rest
        g2.dispose();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame("Pivot Rotate");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(new PivotRotatePanel());
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}

Practical notes and troubleshooting:

  • Rotation uses radians; positive angles are mathematically counterclockwise (screen Y goes down, so visual direction can seem inverted — change sign if needed).
  • If the anchor should be fixed but the line still moves, check for any position deltas (e.g. moveX/moveY) and set them to zero. ’s first sample included motion variables that cause bouncing; that’s the likely cause when the line “won’t stay still.”
  • Put GUI creation on the EDT (SwingUtilities.invokeLater). Don’t start timers or heavy work from paintComponent.
  • For smoothness, prefer ~16ms ticks or a time‑based update (angle += speed * deltaSeconds) so animation is framerate independent. Keep coords in doubles and cast to ints only when drawing to avoid jitter.
  • Use antialiasing and BasicStroke for a nicer hand; for very high performance consider BufferStrategy or a lightweight game loop (or JavaFX) instead of Swing Timer.

Recommended Answers

All 5 Replies

Ok, here's something to play with

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class LinePanel extends JPanel {

    Timer animationTimer;
    float angle = 0f;
    int lineLen = 60;
    int x = 20;
    int y = 20;
    int moveX = 2;
    int moveY = 2;
    double angleChange = Math.PI/20;

    public LinePanel() {
        animationTimer = new Timer(50, new LineAnimation());
        animationTimer.start();
    }

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

        double dx = Math.cos(angle) * lineLen;
        double dy = Math.sin(angle) * lineLen;
        g2d.clearRect(0, 0, getWidth(), getHeight());
        g2d.setColor(Color.BLUE);
        g2d.drawLine((int)(x - dx), (int)(y + dy), (int)(x + dx), (int)(y - dy));
    }

    class LineAnimation implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            angle += angleChange;
            x += moveX;
            y += moveY;
            if (x < 0 || x > getWidth()) {
                moveX *= -1;
                angleChange *= -1;
            }
            if (y < 0 || y > getHeight()) {
                moveY *= -1;
                angleChange *= -1;
            }
            repaint();
        }
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new LinePanel());
        f.setBounds(100, 100, 300, 300);
        f.setVisible(true);
    }
}

Haha m8 that is fantastic, see even that is to advanced for me i cant get it to stay still!

So how do i get that to turn as if one side was pinned down? like a clock, seriously i cant do it not even from that code, I really hate graphics it doesnt make any sense to me.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class LinePanel2 extends JPanel {

    Timer animationTimer;
    int lineLen = 50;   // length of the line
    int x = 65;    // x anchor
    int y = 65;    // y anchor
    float angle = 0f;   // angle of the line
    double angleChange = Math.PI/20;    // rotation per tick

    public LinePanel2() {
        // start the timer firing every 50ms
        animationTimer = new Timer(50, new LineAnimation());
        animationTimer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        // this just makes the line look smoother, less pixelation when at an angle
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // calc the x and y offsets based on the current angle and line length
        double dx = Math.cos(angle) * lineLen;
        double dy = Math.sin(angle) * lineLen;
        // clear the area and draw the line
        g2d.clearRect(0, 0, getWidth(), getHeight());
        g2d.setColor(Color.BLUE);
        g2d.drawLine(x, y, (int)(x + dx), (int)(y - dy));
    }

    class LineAnimation implements ActionListener {
        // this gets called every "tick" of the timer
        public void actionPerformed(ActionEvent e) {
            // change angle and repaint
            // subtracting for clockwise motion
            angle -= angleChange;
            repaint();
        }
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new LinePanel2());
        f.setBounds(100, 100, 200, 200);
        f.setVisible(true);
    }
}

Dude seriously i couldn't be more greatful. Thank you so much I've spent ages looking at so much stuff on animation and i really get that. Seriously I cant thank you enough, you rock!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.