0

2 週間前に Java の学習を始めたばかりなので、Java についてはまだあまり理解していません。フレーム内でボールをバウンドさせたり、動かしたりしようとしています。しかし、スレッドで実行すると再描画/更新されませんが、代わりに while ループまたはタイマーを使用すると問題なく動作します。何が間違っているのかわかりません。これはスレッドのバージョンです:

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

2 に答える 2

2

2 つの異なる Ball オブジェクトを使用しています。

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


       Ball ball1 = new Ball();

順序を変更します。

       Ball ball1 = new Ball();
       Thread t1 = new Thread(ball1);
于 2013-06-02T19:42:17.103 に答える
0

Swing はスレッドセーフではありません。メインスレッドから repaint を呼び出す必要があります。

于 2013-06-02T19:42:43.797 に答える