2016-10-18 14 views
1

Ich habe 2 Klassen namens Game.java und KeyInput.java. Wie greife ich auf int x und int y von Game.java und verwenden Sie in KeyInput.java?Zugriff auf Variablen aus einer anderen Klasse

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" 
    } 
} 

Antwort

2

Das Problem, das Sie haben, werden mit dem Umfang ist. Es gibt viele Möglichkeiten, dies zu beheben, z. B. statische Variablen zu verwenden oder einen Zeiger an das Objekt zu übergeben, das die Variablen enthält, auf die Sie zugreifen möchten. Ich gebe dir nur zwei.

Statisch: Nicht empfohlen, funktioniert aber gut für kleine Programme. Sie können nur eine Menge von x und y haben. Wenn Sie zwei Instanzen des Spiels haben, teilen sie dieselben Werte.

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 
    } 

Pass-in-Methode:

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

vielen Dank! – Sean

+0

Hey, kein Problem! :) – ldmtwo

Verwandte Themen