I created a program that draws and moves a rectangle but it vibrates approx. every 15 seconds.
Here is my code so far:
public class Game extends JPanel implements Runnable {
int x = 0;
int y = 0;
public static void main(String[] args) {
Game game = new Game();
game.start();
}
Game() {
JFrame frame = new JFrame();
frame.add(this);
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
void start() {
Thread thread = new Thread(this);
thread.start();
}
public void run() {
while (true) {
x++;
y++;
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLUE);
g.fillRect(x, y, 100, 100);
}
}
Questions
- Why is the rectangle vibrating while moving?
- How do I fix it?