repaint()不在Thread中工作

时间:2013-06-02 19:39:09

标签: java multithreading swing animation repaint

我刚开始在2周前开始学习java所以我对Java还没有太多了解。我正试图让球反弹或在框架内移动。但是当我在一个线程中运行它时,它不会重新绘制/更新,但是如果我使用while循环或Timer,它可以正常工作,我不明白我做错了什么。这是Thread版本:

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;
        }       
    }
}

2 个答案:

答案 0 :(得分:2)

您正在使用两个不同的Ball对象:

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


       Ball ball1 = new Ball();

更改顺序:

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

答案 1 :(得分:0)

Swing不是线程安全的。你必须从主线程调用重绘。