title: Move object with mouse cursor - Java
body: <p>I have to do the Agario game using object oriented programming with Java. So far I've draw a circle and I was able to make it follow my cursor. However I have many bugs like the ball not following the cursor after the cursor touches the ball, sometimes, the ball moves to quickly, other times it moves to slowly. </p>
  
  <p>Overall I think it's far from perfect and would like some suggestions. I just have to make it follow and I'm struggling a bit. Here's the code: </p>
  
  <p>window class:</p>
  
  <pre><code>public class window extends JFrame implements Runnable {
  
    Ball b = new Ball();
    Thread t = new Thread(this);
  
    public window () {
      setSize(600, 600);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setResizable(true);
      setLocationRelativeTo(null);
      setVisible(true);
      t.start();
  
      addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
          public void mouseMoved(java.awt.event.MouseEvent evt) {
              formMouseMoved(evt);
          }
  
      });
  
    }
  
    private void formMouseMoved(MouseEvent evt) {
      b.setnewtarget(evt.getX(), evt.getY());
    }
  
    @Override
    public void paint(Graphics g) {
      super.paint(g); //To change body of generated methods, choose Tools | Templates.
      b.drawCenteredCircle(g);
    }
  
    public static void main(String[] args) {
      new window ();
    }
  
    @Override
    public void run() {
      while (true) {
          repaint();
      }
    }
  </code></pre>
  
  <p>}</p>
  
  <p>Here´s the Ball class: </p>
  
  <pre><code>public class Ball implements Runnable {
  
    Thread t = new Thread(this);
    int x, y, r;
    int targetx, targety;
  
    public Ball() {
      x = 300;
      y = 300;
      r = 35;
      t.start();
    }
  
    public void drawCenteredCircle(Graphics g) {
      g.fillOval(x, y, r, r);
      g.drawLine(x, y, targetx, targety);
    }
  
    @Override
    public void run() {
      while (true) 
  
           int dx = Math.abs(targetx-x);
           int dy = Math.abs(targety-x);
  
           if (dx &gt; dy) {
              int oldx = x;
              if (x &gt; targetx)
                 x--;
              else
                 x++;
  
              y =((targety-y)/(targetx-x))*(x-oldx)+y;
           } else {
              int oldy = y;
              if (y &gt; targety)
                 y--;
              else
                 y++;
  
              x =((targetx-x)/(targety-y))*(y-oldy)+x;
           }
  
          try {
              t.sleep(10);
          } catch (InterruptedException ex) {
              Logger.getLogger(Bola.class.getName()).log(Level.SEVERE, null, ex);
          }
  
      }
    }
  
    void setnewtarget(int x, int y) {
      targetx = x;
      targety = y;
    }
  }
  </code></pre>
  
  <p>Thanks :D</p>