How can I print a variable into a JPanel and then use the main method to re-print the variable when it changes?

时间:2015-12-10 02:05:33

标签: java variables methods jpanel main

Here's my code; https://gist.github.com/anonymous/b8ef69a391c6c4e37b92

I've tried placing the "label1.setText("Bouncing bouncing ball" + bounceCount);" into the main method, but of course the variable bounceCount is a class variable and cannot be used inside the main method, is there any way around this?

1 个答案:

答案 0 :(得分:0)

这里有两个选择。

  1. 添加“getter”'你的游戏课中的方法。
  2.     private readonly HashSet<char> _operators = new HashSet<char>() { '+', '*', '-', '/' };
    
        void AppendOperator(string operation)
        {
            char lastChar = Result.Text.LastOrDefault();
            if (_operators.Contains(lastChar)) return;
    
            Result.Text = num.ToString() + operation;
        }
    

    然后:

    public int getBounceCount() {
        return bounceCount;
    }
    
    1. 你的第二个选择(以及更好的选择)是让你的主游戏循环在不同的线程中。你甚至可以实现&#39; runnable&#39;你班上的界面。
    2.    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
          }
        }
      }