0

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?
  • 3
    You shouldn't be accessing swing components from any thread other than the event dispatch thread. Use [`javax.swing.Timer`](http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html) to schedule tasks. – RealSkeptic Feb 28 '15 at 11:31
  • 3
    `paintComponent` can be called for any number of reasons. `repaint` requests can also be consolidated down to a single (or lesser) actual events. Any of these combinations could be causing you issues – MadProgrammer Feb 28 '15 at 12:34
  • 2
    See also [*Initial Threads*](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html) and [*How to Use Swing Timers*](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html). – trashgod Feb 28 '15 at 14:43

0 Answers0