2016-10-18 26 views
1

我有两个类叫做Game.javaKeyInput.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" 
    } 
} 

回答

2

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

静态:不推荐,但适用于小程序。你只能有一组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 
... 
+0

非常感谢你! – Sean

+0

嘿,没问题! :) – ldmtwo