gpt4 book ai didi

java - 如何从不同的类访问变量

转载 作者:行者123 更新时间:2023-11-30 00:56:14 25 4
gpt4 key购买 nike

我有 2 个类,分别是 Game.javaKeyInput.java。如何从 Game.java 访问 int x 和 int y 并在 KeyInput.java 中使用?

游戏.java

public class Game extends JFrame {

int x, y;

//Constructor
public Game(){
setTitle("Game");
setSize(300, 300);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addKeyListener(new KeyInput());

x = 150;
y = 150;
}

public void paint(Graphics g){
g.fillRect( x, y, 15, 15);
}

public static void main(String [] args){
new Game();
}
}

KeyInput.java

public class KeyInput extends KeyAdapter {

public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();

if(keyCode == e.VK_W)
y--; //Error here saying "y cannot be resolved to a variable"
}
}

最佳答案

您遇到的问题与范围有关。有很多方法可以解决这个问题,例如使用静态变量或将指针传递给包含您要访问的变量的对象。我给你两个。

静态:不推荐,但适用于小程序。你只能有一组 x 和 y。如果您有两个 Game 实例,它们将共享相同的值。

public class Game extends JFrame {
//make this static and public so it can be accessed anywhere.
public static int x, y;
...
}
...
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();

if(keyCode == e.VK_W)
Game.y--; //Static access
}

传入方式:

public class KeyInput extends KeyAdapter {
Game game; //need a pointer to the original class object that holds x and y. Save it here
public KeyInput(Game g){ //get the object pointer when this class is created.
this.game = g;
}

public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();

if(keyCode == e.VK_W)
game.y--; //now a local variable we can access
}
}


public class Game extends JFrame {
//make these public
public int x, y;

//Constructor
public Game(){
setTitle("Game");
setSize(300, 300);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addKeyListener(new KeyInput(this)); //pass the pointer in here
...

关于java - 如何从不同的类访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40119334/

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