【问题标题】:How can I print a variable into a JPanel and then use the main method to re-print the variable when it changes?如何将变量打印到 JPanel 中,然后在变量更改时使用 main 方法重新打印变量?
【发布时间】:2016-03-15 12:49:03
【问题描述】:
【问题讨论】:
-
请不要链接——所有代码都应与您的帖子一起放在此处。一方面,没有必要这样做,因为如果您的代码太大而无法在此处发布,那么要求志愿者通过就太大了。同样,请记住我们都是志愿者,因此您应该尽量让我们为您提供帮助。因此,请通过在此处发布您的代码来帮助我们解决您的问题,最好是 minimal reproducible example。
标签:
java
variables
methods
jpanel
main
【解决方案1】:
这里有两个选择。
- 在您的游戏类中添加一个“getter”方法。
public int getBounceCount() {
return bounceCount;
}
然后:
while (true) {
game.moveBall();
game.checkBounceCount();
//JLabel label1 = new JLabel();
//label1.setText("Bouncing bouncing ball" + game.getBounceCount());
game.repaint();
Thread.sleep(10);
}
- 您的第二个选择(也是一个更好的选择)是将您的主游戏循环放在不同的线程中。您甚至可以在您的类中实现“可运行”接口。
public class Game extends JPanel implements Runnable {
//...
public void run() {
//Your game's main animation loop
while (true) {
//Do your thing
}
}
}
然后在main方法中:
Thread gameLoop = new Thread(game);
gameLoop.start();