Sean Sean - 1 month ago 10
Android Question

How to access variables from a different class

I have 2 classes called Game.java and KeyInput.java. How do I access int x and int y from Game.java and use to in 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"
}


}

Answer

The issue you are having is with the scope. There are many ways to fix this, such as using static variables or passing a pointer to the object that contains the variables you want to access. I'll just give you two.

Static: Not recommended, but works well for small programs. You can only have one set of x and y. If you have two instantiations of Game, they will share the same values.

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 method:

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 
...