title: java repaint multiple area
body: <p>I want to draw specific area on JPanel, like this (black area is where I want JPanel to be repainted):</p>
  
  <p><a href="https://i.stack.imgur.com/cTj71.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cTj71.png" alt="enter image description here"></a> </p>
  
  <p>Below code is how I implemented this. It follows mouse cursor and draws a circle at the mouse cursor point. The size of frame and panel is 300*300.</p>
  
  <pre><code>public class MiniGraphicTest extends JPanel{
  
  private static final long serialVersionUID = 1L;
  
  public int x,y;
  public MiniGraphicTest() {
      super();
      x = -1;
      y = -1;
      addMouseMotionListener(new MouseMotionAdapter(){
          @Override
          public void mouseMoved(MouseEvent m){
              x = m.getX()-25;
              y = m.getY()-25;
              repaint(100,100,100,100);
              repaint(200,200,100,100);
          }
      });
  }
  protected void paintComponent(Graphics g){
      super.paintComponent(g);
      //////////////////////
      //DO NOT MODIFY HERE//
      //////////////////////
      //Draw gridline
      int width = this.getWidth();
      int height = this.getHeight();
      g.setColor(Color.BLACK);
      for(int i=100;i&lt;width;i+=100){
          g.drawLine(i, 0, i, height);
      }
      for(int i=100;i&lt;height;i+=100){
          g.drawLine(0, i, width, i);
      }
      //////////////////////
      //put test code here//
      //////////////////////
      if(x == -1&amp;&amp;y==-1) return;//initially draw nothing
      g.fillOval(x, y, 50, 50);
  }
  }//main function is just showing the panel. nothing special
  public static void main(String[] args) {
      JFrame jf = new JFrame("Test");
      MiniGraphicTest test = new MiniGraphicTest();
      jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      test.setPreferredSize(new Dimension(300, 300));
      jf.setResizable(false);
      jf.add(test);
      jf.pack();
      jf.setVisible(true);
  }
  </code></pre>
  
  <p>The result of this code is like this : </p>
  
  <p><a href="https://i.stack.imgur.com/i45su.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i45su.png" alt="enter image description here"></a></p>
  
  <p>It repaints outside of the area to be repainted. Can you explain me why this happened and how to solve this?</p>
  
  <p>PS. The code completely works well when only single repaint(100,100,100,100) is called in the mouseMoved.</p>
  
  <p>Thank you</p>