【问题标题】: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
【问题描述】:

这是我的代码; https://gist.github.com/anonymous/b8ef69a391c6c4e37b92

我试过放置“label1.setText(“Bouncing bouncing ball”+bounceCount);”进入main方法,但是bounceCount这个变量当然是类变量,不能在main方法内部使用,有什么办法解决吗?

【问题讨论】:

  • 请不要链接——所有代码都应与您的帖子一起放在此处。一方面,没有必要这样做,因为如果您的代码太大而无法在此处发布,那么要求志愿者通过就太大了。同样,请记住我们都是志愿者,因此您应该尽量让我们为您提供帮助。因此,请通过在此处发布您的代码来帮助我们解决您的问题,最好是 minimal reproducible example

标签: java variables methods jpanel main


【解决方案1】:

这里有两个选择。

  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);
    }
  1. 您的第二个选择(也是一个更好的选择)是将您的主游戏循环放在不同的线程中。您甚至可以在您的类中实现“可运行”接口。

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();

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    相关资源
    最近更新 更多