-1

I have created a program that draws a thick line.

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

public class Movement {
    int xGrid = 50;

    public static void main(String[] args) {

        Movement m = new Movement();
        m.animate();
    }

    public void animate() {

        JFrame frame = new JFrame("Movement");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ScreenDisplay display = new ScreenDisplay();

        frame.getContentPane().add(display);
        frame.setSize(400, 400);
        frame.setVisible(true);

        for (int aL = 0; aL < 200; aL++) {

            xGrid++;

            display.repaint();

            try {

                Thread.sleep(50);
            } catch (Exception ex) { }
        }
    }

    class ScreenDisplay extends JPanel {
        public void paintComponent(Graphics g) {

            g.setColor(Color.RED);
            g.fillOval(xGrid, 175, 50, 50);
        }
    }
}

Because of the method "Thread.sleep(50)", the speed of the program slows down a little.

So I got a little curious and removed the "sleep()" method.

What I expected to output was the exact same output, just extremely fast.

However, it just prints out one circle in the frame.

I don't really know why it outputs just one circle, none of the researches I've done back up the answer.

Can anyone please explain why?

Kcits970
  • 640
  • 1
  • 5
  • 23
  • In the second example, the requests for repainting are queued, and you end up only seeing the result of the last one. With the `sleep`, you actually see the several repaints occuring . – Arnaud Sep 02 '16 at 12:51
  • You never call `super.paintComponent` in `ScreenDisplay`. That's going to make the graphics behave unpredictably. – resueman Sep 02 '16 at 12:54
  • Ahh, okay, thx for the answer, it really helped me tremendously! :) – Kcits970 Sep 02 '16 at 12:54
  • 2
    Possible duplicate of [Difference between wait() and sleep()](http://stackoverflow.com/questions/1036754/difference-between-wait-and-sleep) – xenteros Sep 02 '16 at 12:56
  • Thread.sleep() does not pause the _program_, it pauses the one thread within the program that called it. Other threads continue to run. If the program's threads are not well _synchronized_, then adding a sleep(), removing a sleep(), or changing the length of a sleep() potentially could alter the behavior and the correctness of the program. – Solomon Slow Sep 02 '16 at 12:56

1 Answers1

2

From Component.repaint documentation:

Repaints this component.

If this component is a lightweight component, this method causes a call to this component's paint method as soon as possible. Otherwise, this method causes a call to this component's update method as soon as possible.

By the looks of it, your for loop finishes so quickly that by the time the component calls the repaint method, it has already finished and therefore only paints the final circle stored in the buffer.