Why the object don't track the mouse when drag the mouse quickly with mouseMoved?

41 views Asked by At

I'm building a game that I want an object to stay still initially, and when I move the mouse over it, I want the object to follow the mouse. However, when I run the program, I find that it works, but when I move the mouse quickly, the object detaches from the mouse. How should I solve this issue?

Here is my code:

public class Test extends JFrame {
    private static int barX = 8;
    private static int barY = 31;
    DrawWorld canvas;
    private int startX = 100 - barX;
    private int startY = 100 - barY; 
    private int sizeBox = 30;
    private Color colorBox = Color.GREEN;

    public Test() {
        canvas = new DrawWorld();
        setPreferredSize(new Dimension(1366, 768));
        setLayout(new FlowLayout());
        setContentPane(canvas);

        addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                int cursorX = e.getX();
                int cursorY = e.getY();
                if ((cursorX > startX && cursorX < startX + sizeBox) || (cursorY > startY && cursorY < startY + sizeBox)){
                    // The box Follow mouse 
                    startX = cursorX - barX - sizeBox / 2;
                    startY = cursorY - barY - sizeBox / 2;
                }
                System.out.println(e.getPoint());
                repaint();
            
            }
        });

        // Frame
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Game");
        pack();
        setVisible(true);
        repaint();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }

    public void paintBox(Graphics g) {
        g.setColor(colorBox);
        g.fillRect(startX, startY, sizeBox, sizeBox);
    }

    private class DrawWorld extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // paintBox(g);
            Graphics2D g2d = (Graphics2D) g;
            Shape sqaure = new Rectangle(startX, startY, sizeBox, sizeBox);
            g2d.fill(sqaure);
        }
    }
}
0

There are 0 answers