java 更改另一个类中静态变量的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35760019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:33:18  来源:igfitidea点击:

Changing the value of static variables in another class

java

提问by Charlie Landrigan

I am trying to display a character moving across the screen but the x and y variables stay the same. I am under the impression that when I change the value of a static variable it changes in every instance of the class.

我试图显示一个在屏幕上移动的字符,但 x 和 y 变量保持不变。我的印象是,当我更改静态变量的值时,它会在类的每个实例中更改。

here is the class where is meant to move the character

这是用于移动角色的课程

public class MoveChara {
 private static int x, y;
 private int dx, dy;

 public void init() {
  x = 30;
  y = 50;
  dx = 1;
  dy = 1;
 }

 public void move() {
  x += dx;
  y += dy;
 }

 public int getX() {
  return x;
 }

 public int getY() {
  return y;
 }
}

here is part of the class that calls the move method

这是调用 move 方法的类的一部分

public class Game implements Runnable {
 private MoveChara move;
 private boolean running = false;

 public void run() {
  init();

  while(running) {
   tick();
   render();
  }
  stop();
 }

 private void init()  {
  move = new MoveChara;
 }

 private void tick() {
  move.move();
 }
}

and in the method that draws the character

并在绘制字符的方法中

public class Draw extends JPanel {
 public MoveChara move;
 public ImageMake imgm;

 @Override
 public void paintComponent(Graphics g) {
  imgm = new ImageMake();
  super.paintComponent(g);
  Graphics2D g2d = (Graphics2D) g;

  move = new MoveChara();
  move.init();
  g2d.drawImage(
   imgm.createImg("Images/SpriteSheet.png"),
   move.getX(),
   move.getY(),
   this
  );
 }
}

回答by goncalopinto

A static variable belongs to the class not to an instance of the class. To access a static variable from outside of its class you can do it like this:

静态变量属于类而不属于类的实例。要从其类外部访问静态变量,您可以这样做:

claasName.variablename = newValue;

Inside the paintComponentmethod there is a call to the init method in the parent class, this is initializing x and y everytime it is called. If you move the initialization to the static variables declarations this dhould work. Let me know if it's this you are looking for.

在该paintComponent方法内部调用了父类中的 init 方法,每次调用时都会初始化 x 和 y。如果您将初始化移动到静态变量声明,这应该可行。如果这就是您要找的,请告诉我。

回答by Top Sekret

Static variables are shared across instances of the class. When edited, they change for all instances.

静态变量在类的实例之间共享。编辑后,它们会更改所有实例。