0

我一直在编写一个球在墙上弹跳的项目,除了当我将鼠标足够快地移动到绘图面板上时,一切工作正常,重绘是滞后的。所以我在Edit 2中做了一个例子,问题也存在。为什么?我该如何修复它或解决它?

编辑 1: 这就是我的代码的样子:这里
编辑 2: 我创建了这个示例以使其更清晰。

import javax.swing.*;
import java.awt.*;

import static javax.swing.JFrame.EXIT_ON_CLOSE;

public class DrawingPanel extends JPanel
{
    public Ball ball;
    public DrawingPanel()
    {
        super();
        setPreferredSize(new Dimension(300, 100));
        setBackground(Color.black);
        this.ball = new Ball(10);
        this.ball.start();
    }
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Laggy ball");
        DrawingPanel panel = new DrawingPanel();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
        while(true)
        {
            try
            {
                Thread.sleep(17);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            panel.repaint();
        }
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        ball.draw(g);
    }

    public class Ball extends Thread
    {
        public int position;
        public int velocity;
        public Ball(int velocity)
        {
            super();
            this.position = 0;
            this.velocity = velocity;
        }
        void draw(Graphics g)
        {
            g.setColor(Color.blue);
            g.fillOval(position, 50, 20, 20);
        }
        void update()
        {
            position += velocity;
            if(position > getWidth() || position < 0)
                velocity *= -1;
        }
        @Override
        public void run()
        {
            while(true)
            {
                try
                {
                    Thread.sleep(17);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                update();
            }
        }
    }
}

编辑3: 解决了一个问题。至少我知道问题不在于代码,而在于我的笔记本电脑。

编辑 4: 我注意到问题只存在于使用外接鼠标时。否则一切都好。这是与代码无关的本地问题。不过谢谢你的帮助!

4

0 回答 0