Jole Mola
Jole Mola

Reputation: 25

repaint() not working in a Thread

i just started learning java 2 weeks ago so i don't really understand to much about java yet.I'm trying to make a ball bounce around or move around inside the frame. but it doesn't repaint/update when i run it in a Thread, but it works just fine if i use a while loop or a Timer instead, I don't understand what I'm doing wrong. This is the Thread version:

public class Game {

    public static void main(String args[]){
        Thread t1 = new Thread(new Ball());
        Ball ball1 = new Ball();
        JFrame frame = new JFrame("Breakout");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBackground(Color.WHITE);
        frame.setSize(1000, 1000);
        frame.setVisible(true);
        frame.add(ball1);
        t1.start();     
      }
    }    

    public class Ball extends JPanel implements Runnable{
     public int x = 5, y = 5;
     public int speedx = 5, speedy = 5;
     public int width = 30, height = 30;
     public void run() {            
         while (true){  
            try {                   
                Physics();
                repaint();
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }               
            }           
        }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.fillOval(x, y, width, height);            
    } 

    public void Physics(){
        x += speedx;
        y += speedy;
        if(0 > x || x > 1000){
            speedx = -speedx;
        }
        if(0 > y || y > 1000){
            speedy = -speedy;
        }       
    }
}

Upvotes: 0

Views: 2882

Answers (2)

exoon
exoon

Reputation: 39

Swing is not thread safe. You have to call repaint from the main thread.

Upvotes: 0

xtraclass
xtraclass

Reputation: 445

You are using two different Ball objects:

       Thread t1 = new Thread(new Ball());


       Ball ball1 = new Ball();

Change the order:

       Ball ball1 = new Ball();
       Thread t1 = new Thread(ball1);

Upvotes: 2

Related Questions