title: Execute a part of code in specified time
body: <p>I want to make an animation using java swing. I have a for loop that changes the location of an image slightly. My question is <strong>How can I make the each loop execution takes the specified amount of time?</strong>.
  Its what I've done but I don't know how to use <code>wait()</code> and don't know is there a better way.</p>
  
  <pre><code>// inside of a MyJPanel class extending JPanel
  for (int i = 0; i &lt; FJframe.FRAMES; i++){
      long start = System.currentTimeMillis();
      animationFrame = i;
      this.repaint();
      long end = System.currentTimeMillis();
      long remainder = (end - start);
      System.out.println(remainder);
      try {
          this.wait(200 - remainder);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <hr>
  
  <h2>Edit</h2>
  
  <p>here my overrided Jpanel <code>PaintComponent()</code>:
      //some drawing
      drawChanges(g, getDelta(), animationFrame, FJPanle.FRAMES);</p>
  
  <p>And inside drawChanges(Graphics g, ArrayList deltas, int frame, int frames):</p>
  
  <pre><code>// a switch_case with cases similar to this one.
  case AGENT_ATTACK:
  // tu phase badi animation e kill
      //drawImage(g2d, map[delta.getCell().x][delta.getCell().y], attacker);
      source = map[delta.getSource().x][delta.getSource().y];
      dest = map[delta.getDestination().x][delta.getDestination().y];
      distanceX =  dest.getCenter().x -
              source.getCenter().x;
      distanceY = dest.getCenter().y -
              source.getCenter().y;
      if (counter &lt; frames / 2){
          g2d.drawImage(ImageHolder.attacker, source.getBounds().x + (int)(((float)counter/frames) * distanceX),
                  source.getBounds().y + (int)(((float)counter/frames) * distanceY),
                  null);
      }
      else{
          g2d.drawImage(ImageHolder.attacker, dest.getBounds().x - (int)(((float)counter/frames) * distanceX),
                  dest.getBounds().y - (int)(((float)counter/frames) * distanceY),
                  null);
      }
      break;
  </code></pre>
  
  <hr>
  
  <p>I want each loop takes, for example, exactly 200 miliseconds. How can I achieve this?</p>