2016-10-18 29 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