title: Moving Java Swing rectangle leaves rectangles behind
body: <p>When I finally figured out the repaint method, I came to a problem. I want to move a rectangle across the screen, rather than re-drawing it again. Redrawing is fine, but it leaves the older rectangle behind it! This is my code:</p>
  
  <pre><code>import java.awt.Dimension;
  import java.awt.Graphics;
  import java.awt.Graphics2D;
  import java.util.logging.Level;
  import java.util.logging.Logger;
  import javax.swing.JFrame;
  import javax.swing.JPanel;
  
  public class Tutorial3{
  
      public static void main(String[] agrs){
          createAndStartGui();
      }
      static void createAndStartGui(){
          JFrame f = new JFrame("tutorial 3");
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.getContentPane().setPreferredSize(new Dimension(500, 300));
  
          MyPanel panel = new MyPanel();
          f.add(panel);
  
          f.pack();
          f.setVisible(true);
  
          for (int i = 0; i &lt; 10; i++){
              try {
                  Thread.sleep(100);
              } catch (InterruptedException ex) {
                  Logger.getLogger(Tutorial3.class.getName()).log(Level.SEVERE, null, ex);
              }
              panel.user.move("right");
              panel.repaint();
          }
      }
  }
  
  class MyRectangle{
      int x;
      int y;
      public MyRectangle(int x, int y){
          this.x = x;
          this.y = y;
      }
      void move(String direction){
          switch (direction){
              case "up":
                  this.y -= 10;
                  break;
              case "down":
                  this.y += 10;
                  break;
              case "left":
                  this.x -= 10;
                  break;
              case "right":
                  this.x += 10;
                  break;
              default:
                  break;
          }
      }
  }
  
  class MyPanel extends JPanel{
      MyRectangle user = new MyRectangle(10, 10);
      public MyPanel(){
  
      }
      public void paintComponent(Graphics g){
          Graphics2D g2d = (Graphics2D) g;
          g.drawRect(user.x, user.y, 10, 10);
      }
  
  }
  </code></pre>
  
  <p>How do I get the rectangle that is left behind disappear (I DO NOT WANT TO CLEAR THE FULL WINDOW)? Or even better yet, how do I get the rectangle to 'move' (if it is possible)?</p>
  
  <p>My end result: </p>
  
  <p><img src="https://i.stack.imgur.com/8NZwG.jpg" alt="enter image description here"></p>
  
  <p>What I want in the end:</p>
  
  <p><img src="https://i.stack.imgur.com/gLpa6.png" alt="enter image description here"></p>
  
  <p>Note: simply drawing the rectangle in that point isn't what I want. I want to see it getting dragged across. </p>