我有两个名为Game.java
和KeyInput.java
的课程。如何从Game.java
访问int x和int y并在KeyInput.java
中使用?
Game.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"
}
}
答案 0 :(得分:1)
您遇到的问题在于范围。有许多方法可以解决此问题,例如使用静态变量或将指针传递给包含要访问的变量的对象。我会给你两个。
静态:不推荐但适用于小型程序。你只能有一组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
...