BisaZ
BisaZ

Reputation: 221

How to loop an array of points with delay in java?

I'm trying to loop trough an array of Points with a delay, but nothing happens and I don't get errors. Here's an example of what my code looks like:

public class Class {    
    private Point[] points;
    private int start, delay;

    public Class() {
        points = new Point[] {
            new Point(1, 1),
            new Point(2, 1),
            new Point(1, 2)
        };
        start = System.nanoTime();
        delay = 500;
    }

    public void update() {
        for(int i = 0; i < points.length; i++) {
            long elapsed = (System.nanoTime() - startT) / 1000000;
            if(elapsed > delay) {
                System.out.println("x: " + points[i].x);
                System.out.println("y: " + points[i].y);
                start = System.nanoTime();
            }
        }
    }
}

Everything inside the update function is working except for that for loop.

edit: It's a java Swing application with only 1 thread.

Upvotes: 1

Views: 533

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

One of your problems is that you're using an if block and not a while loop. An if block just checks once, sees that the condition is false, and skips over it. A while loop will loop until the condition is false.

  • For most delays you could use a general purpose Timer object such as a java.util.Timer together with a java.util.TimerTask object.
  • for delays in a Swing GUI you would use a javax.swing.Timer
  • Other options for general non-Swing computing including using a while loop that contains a Thread.sleep(...) call.
  • Also look into using a ScheduledThreadPoolExecutor for non-Swing delays.

Edit
Regarding your edit:

edit: It's a java Swing application with only 1 thread.

If you need more help, then as we've already mentioned, provide more detail in your question.

Upvotes: 3

AlexWien
AlexWien

Reputation: 28747

To sleep for an aproximate amount of time use Thread.sleep(millis);
Do not expect accuracy to be more than 30ms.

Upvotes: 2

Related Questions