gpt4 book ai didi

java - repaint() 不在线程中工作

转载 作者:行者123 更新时间:2023-12-02 06:59:09 27 4
gpt4 key购买 nike

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

最佳答案

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

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


Ball ball1 = new Ball();

更改顺序:

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

关于java - repaint() 不在线程中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16886562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com