0

I have the following code:

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class Exercise2 extends JFrame implements ActionListener{
    public int x = 20 ,direction = 1;

    public Exercise2(){
         setSize(400, 200);
         setTitle("Moving Car");
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setLayout(new BorderLayout());
         JButton move = new JButton("Move the car");
         move.addActionListener(this);
         add(move , BorderLayout.SOUTH);
         setVisible(true);
    }
    public void paint(Graphics g){
        super.paint(g);
        g.drawRect(x, 80, 80, 50);
            g.drawOval(x, 130, 30, 30);
            g.drawOval(x+50, 130, 30, 30);
    }
    public void actionPerformed(ActionEvent e){
         MyThread ex = new MyThread();
            ex.start();
}



private class MyThread extends Thread {
    public void run(){
        while(true){
            if(x >= getWidth()-70)
                direction = -1;
            else if (x <= 0)
                direction = 1 ;
            x += direction *10;

            try{
                Thread.sleep(100);
            }catch(InterruptedException e){
                System.exit(0);
            }
            repaint();
        }
    }
}



public static void main(String []args){
    new Exercise2();

}
}

the car starts moving when I press the button However it keeps flashing if i don't move the mouse over the button

My Questions : Why did that happen? ** & ** How to solve it?

NEW : I changed the sleep time to 500 and it worked fine but how can it be solved without changing the sleeping time ?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
iShaalan
  • 799
  • 2
  • 10
  • 30

1 Answers1

3

JFrame is redrawing the painting slower than you move the car - when the redrawing is happening, the picture will be "empty" for a short while.

Increase Thread.sleep(100); to Thread.sleep(1000); and see the difference.

Edit: by some googling I found something that could lead to a solution, from My JFrame Flickers:

Don't draw directly in the JFrame in its paint method. Instead draw in a JPanel or JComponent and override its paintComponent method since Swing does double buffering by default, and this will allow you to take advantage of this.

edit2: more on the same in Image flickers on repaint()

Community
  • 1
  • 1
Plux
  • 414
  • 4
  • 15
  • yea I changed it to 500 and it worked fine but isn't there a way to solve it without changing the sleep time ? – iShaalan Nov 20 '13 at 12:43
  • I don't know. I would perhaps guess that the swing frameworks use of jframe is too slow for this here, and its not easily fixable here. But there has to be a way of fixing it, in worst case use another library. – Plux Nov 20 '13 at 13:06