I've been coding a project of balls bouncing of the wall and everything works fine besides when I move the mouse over the drawing panel fast enough, the repaint is laggy. So I made an example in Edit 2 and the problem exists there too. Why? How can I fix it or work around it?
Edit 1:
This is how my code looks like: here
Edit 2:
I created this example to make it more clear.
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();
}
}
}
}
Edit 3: One problem solved. At least I know the problem is not the code but my laptop.
Edit 4: I noticed the problem only exists while using external mouse. Otherwise it's all fine. It was a local problem not with the code. Thanks for help, though!