我两周前刚开始学习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;
}
}
}